Example of using redis in spring boot

Keywords: Redis Spring Java Database

1. Start by creating a spring boot project. See the following links for a way to create a spring boot project:

 https://blog.csdn.net/liutong123987/article/details/79385513

2. Add the following configuration to the pom.xml file that you just created the project

<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-data-redis</artifactId>  
</dependency>

3. Install redis, click exe file to open redies service

4. Create the following classes in the project in turn

public class Author {
	public String name;
	public String intro_l;
	public String getIntro_l() {
		return intro_l;
	}
	public void setIntro_l(String intro_l) {
		this.intro_l = intro_l;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Author(String name, String intro_l) {
		super();
		this.name = name;
		this.intro_l = intro_l;
	}
	public Author() {
		super();
	}
	@Override
	public String toString() {
		return "Author [name=" + name + ", intro_l=" + intro_l + "]";
	}
	
}
import java.lang.reflect.Method;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@EnableCaching
public class RedisConfiguration extends CachingConfigurerSupport {
    /**
     * Customize rules for generating key s
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                //Format Cache key String
                StringBuilder sb = new StringBuilder();
                //Append Class Name
                sb.append(o.getClass().getName());
                //Append method name
                sb.append(method.getName());
                //Traverse parameters and append
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println("call Redis cache Key : " + sb.toString());
                return sb.toString();
            }
        };
    }
    
    /**
     * Using RedisCacheManager as the cache manager
     * @param connectionFactory
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheManager redisCacheManager = RedisCacheManager.create(connectionFactory);
        return  redisCacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        ////Solve key, value serialization issues
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public interface RedisHelper<HK, T> {
    /**
     * Hash Structure Add Element* @param key * @param hashKey hashKey * @param domain element
     */
    void hashPut(String key, HK hashKey, T domain);
    /**
     * Hash Structure gets all key-value pairs for the specified key * @param key * @return
     */
    Map<HK, T> hashFindAll(String key);
    /**
     * Hash Structure gets a single element * @param key * @param hashKey * @return
     */
    T hashGet(String key, HK hashKey);
    void hashRemove(String key, HK hashKey);
    /**
     * List Structure adds elements to the tail (Right)* @param key * @param domain * @return
     */
    Long listPush(String key, T domain);
    /**
     * List Structure adds elements to the header (Left)* @param key * @param domain * @return
     */
    Long listUnshift(String key, T domain);
    /**
     * List Structure Gets All Elements* @param key * @return
     */
    List<T> listFindAll(String key);
    /**
     * List Structure removes and gets the first element of the array * @param key * @return
     */
    T listLPop(String key);
    /**
     * Entity class of object
     * @param key
     * @param domain
     * @return
     */
    void valuePut(String key, T domain);
    /**
     * Get Object Entity Class
     * @param key
     * @return
     */
    T getValue(String key);
    void remove(String key);
    /**
     * Set expiration time* @param key key* @param timeout time* @param timeUnit time unit
     */
    boolean expirse(String key, long timeout, TimeUnit timeUnit);
}
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

@Service("RedisHelper")
public class RedisHelperImpl<HK, T> implements RedisHelper<HK, T> {
    // Get redisTemplate instance in constructor, key(not hashKey) uses String type by default
    private RedisTemplate<String, T> redisTemplate;
    // Instantiate the operation object in the constructor through the redisTemplate factory method
    private HashOperations<String, HK, T> hashOperations;
    private ListOperations<String, T> listOperations;
    private ZSetOperations<String, T> zSetOperations;
    private SetOperations<String, T> setOperations;
    private ValueOperations<String, T> valueOperations;

    // IDEA can be injected successfully even though it has errors. After instantiating the operation object, the method can be called directly to operate the Redis database
    @Autowired
    public RedisHelperImpl(RedisTemplate<String, T> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.hashOperations = redisTemplate.opsForHash();
        this.listOperations = redisTemplate.opsForList();
        this.zSetOperations = redisTemplate.opsForZSet();
        this.setOperations = redisTemplate.opsForSet();
        this.valueOperations = redisTemplate.opsForValue();
    }

    @Override
    public void hashPut(String key, HK hashKey, T domain) {
        hashOperations.put(key, hashKey, domain);
    }

    @Override
    public Map<HK, T> hashFindAll(String key) {
        return hashOperations.entries(key);
    }

    @Override
    public T hashGet(String key, HK hashKey) {
        return hashOperations.get(key, hashKey);
    }

    @Override
    public void hashRemove(String key, HK hashKey) {
        hashOperations.delete(key, hashKey);
    }

    @Override
    public Long listPush(String key, T domain) {
        return listOperations.rightPush(key, domain);
    }

    @Override
    public Long listUnshift(String key, T domain) {
        return listOperations.leftPush(key, domain);
    }

    @Override
    public List<T> listFindAll(String key) {
        if (!redisTemplate.hasKey(key)) {
            return null;
        }
        return listOperations.range(key, 0, listOperations.size(key));
    }

    @Override
    public T listLPop(String key) {
        return listOperations.leftPop(key);
    }

    @Override
    public void valuePut(String key, T domain) {
        valueOperations.set(key, domain);
    }

    @Override
    public T getValue(String key) {
        return valueOperations.get(key);
    }

    @Override
    public void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public boolean expirse(String key, long timeout, TimeUnit timeUnit) {
        return redisTemplate.expire(key, timeout, timeUnit);
    }
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RedisHelperImpl redisHelper;

	@Test
	public void test() throws Exception {
		Author user = new Author();
		user.setName("Alex");
		user.setIntro_l("A program that doesn't play basketball is not a good man");

		// Save data like redis
		redisHelper.valuePut("aaa", user);

		// Getting cached data from key
		Author autor = (Author) redisHelper.getValue("aaa");

		// Delete a data based on the key
		//redisHelper.remove("aaa");
		System.out.println(autor);
	}

	@Test
	public void testObj() throws Exception {
		Author user = new Author();
		user.setName("Jerry");
		user.setIntro_l("A program that doesn't play basketball is not a good man!");

		ValueOperations<String, Author> operations = redisTemplate.opsForValue();
		operations.set("502", user);
		Thread.sleep(500);
		boolean exists = redisTemplate.hasKey("502");
		if (exists) {
			System.out.println(redisTemplate.opsForValue().get("502"));
		} else {
			System.out.println("exists is false");
		}
	}
}

5. Configure the following in application.properties

spring.redis.database=0 
spring.redis.host=192.168.0.32
spring.redis.port=6379 
spring.redis.password=  
spring.redis.pool.max-active=8 
spring.redis.pool.max-wait=-1 
spring.redis.pool.max-idle=8 
spring.redis.pool.min-idle=0 
spring.redis.timeout=5000

Do not configure timeout too small, otherwise connection timeout will be missed

6. Running the test method in the TestRedis class you just created saves a piece of data in redis with aaa as the key. Open the redis client and enter the command get aaa to see the data you just written.

Posted by splitinfo on Wed, 15 Jan 2020 08:07:13 -0800