[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)

spring.redis.database=0

Redis server address

spring.redis.host=127.0.0.1

Redis server connection port

spring.redis.port=6379

Redis server connection password (default is empty)

spring.redis.password=

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

spring.redis.pool.max-active=8

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

spring.redis.pool.max-wait=-1

The largest idle connection in the connection pool

spring.redis.pool.max-idle=8

The smallest in the connection pool Idle connection

spring.redis.pool.min-idle=0

connection timeout (ms)

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

@Bean
Public KeyGenerator keyGenerator() {
    Return new KeyGenerator() {
        @Override
        Public Object generate(Object target, Method method, Object... params) {
            StringBuilder sb = new StringBuilder();
            Sb.append(target.getClass().getName());
            Sb.append(method.getName());
            For (Object obj : params) {
                Sb.append(obj.toString());
            }
            Return sb.toString();
        }
    };
}

@SuppressWarnings("rawtypes")
@Bean
Public CacheManager cacheManager(RedisTemplate redisTemplate) {
    RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
    / / Set the cache expiration time
    //rcm.setDefaultExpiration(60);//sec
    Return rcm;
}

@Bean
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);
    om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    jackson2JsonRedisSerializer.setObjectMapper(om);
    template.setValueSerializer(jackson2JsonRedisSerializer);
    template.afterPropertiesSet();
    Return template;
}

}

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

@Autowired
private StringRedisTemplate stringRedisTemplate;

@Autowired
private RedisTemplate redisTemplate;

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

@Test
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);
    Thread.sleep(1000);
    //redisTemplate.delete("com.neo.f");
    boolean exists=redisTemplate.hasKey("com.neo.f");
    if(exists){
        System.out.println("exists is true");
    }else{
        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