[springboot] (five) integration redis

spring boot support for common database, the nosql database is also packaged automation. Redis introduction Redis is the most widely used memory data storage in the industry. Compared to memcached, Redis supports richer data structures such as hashes, lists, sets, etc., while supporting data persistence. In addition, Redis also provides some database-like features, such as transactions, HA, and master-slave libraries. It can be said that Redis has some features of the cache system and database, so it has a rich application scenario. This article describes two typical application scenarios of Redis in Spring Boot. how to use 1. Introduce the spring-boot-starter-data-redis jar package. Do not use it wrong.       Org.springframework.boot     Spring-boot-starter-data-redis   2, add configuration file

REDIS (RedisProperties)

Redis database index (default is 0)


Redis server address


Redis server connection port


Redis server connection password (default is empty)


连接The maximum number of connections in the pool (using a negative value means no limit)


Connection pool maximum blocking wait time (using a negative value means no limit)


The largest idle connection in the connection pool


The smallest in the connection pool Idle connection


connection timeout (ms)

spring.redis.timeout=100000 3, add the cache configuration class @Configuration @EnableCaching Public class RedisConfig extends CachingConfigurerSupport{

Public KeyGenerator keyGenerator() {
    Return new KeyGenerator() {
        Public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            For (Object obj : params) {
            Return sb.toString();

Public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    / / Set the cache expiration time
    Return rcm;

Public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
    StringRedisTemplate template = new StringRedisTemplate(factory);
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
    ObjectMapper om = new ObjectMapper();
    om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    Return template;


3, well, then you can use it directly. @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) Public class TestRedis {

private StringRedisTemplate stringRedisTemplate;

private RedisTemplate redisTemplate;

public void test() throws Exception {
    stringRedisTemplate.opsForValue().set("aaa", "111");
    Assert.assertEquals("111", stringRedisTemplate.opsForValue().get("aaa"));

public void testObj() throws Exception {
    User user=new User("[email protected]", "aa", "aa123456", "aa","123");
    ValueOperations<String, User> operations=redisTemplate.opsForValue();
    operations.set("com.neox", user);
    operations.set("com.neo.f", user,1,TimeUnit.SECONDS);
    boolean exists=redisTemplate.hasKey("com.neo.f");
        System.out.println("exists is true");
        System.out.println("exists is false");
   // Assert.assertEquals("aa", operations.get("com.neo.f").getUserName());


The above are all manual methods, how to automatically use the cache when looking up the database, see below; @Cacheable and @CacheEvict. The first annotation represents querying the specified key from the cache. If it is, it is taken from the cache and the method is no longer executed. If not, the method is executed. Line method, and the method's return value is associated with the specified key, put into the cache. @CacheEvict is to clear the data corresponding to the specified key from the cache 4, automatically generate a cache according to the method @RequestMapping("/getUser") @Cacheable(value=”user-key”) Public User getUser() {     User user=userRepository.findByUserName("aa");     System.out.println("If the word "call without buffer" appears below and the data can be printed to indicate that the test was successful");     Return user; } The value of value is the key cached in redis Share Session-spring-session-data-redis In distributed systems, sessiong sharing has many solutions, and hosting to the cache should be one of the most commonly used solutions. Spring Session official description Spring Session provides an API and implementations for managing a user’s session information. how to use 1. Introducing dependencies       Org.springframework.session     Spring-session-data-redis   2, Session configuration: @Configuration @EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30) Public class SessionConfig { } maxInactiveIntervalInSeconds: Set the session expiration time. After using the Redis Session, the original Boot's server.session.timeout attribute no longer takes effect. Ok, so it's configured, let's test it. 3, test Add a test method to get the sessionid @RequestMapping("/uid")     String uid(HttpSession session) {         UUID uid = (UUID) session.getAttribute("uid");         If (uid == null) {             Uid = UUID.randomUUID();         }         session.setAttribute("uid", uid);         Return session.getId();     } Login redis input keys ‘sessions’ t