11. Use of Redis in Spring Boot

Reprinted: http://www.cnblogs.com/ityouknow/p/5748830.html


Besides the support of common database by spring boot, nosql database is also encapsulated and automated.

Introduction to redis

Redis is the most widely used memory data storage in the industry. Redis supports richer data structures than memcached, such as hashes, lists, sets, and data persistence. In addition, Redis also provides some features of class databases, such as transactions, HA, master-slave libraries. It can be said that Redis combines some features of caching system and database, so it has rich application scenarios. This paper introduces two typical application scenarios of Redis in Spring Boot.

How to use it

1. Introducing spring-boot-starter-redis

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

2. Adding Configuration Files

# REDIS (RedisProperties)
# Redis database index (default 0)
spring.redis.database=0  
# Redis server address
spring.redis.host=192.168.0.58
# Redis Server Connection Port
spring.redis.port=6379  
# Redis server connection password (default is empty)
spring.redis.password=  
# Maximum number of connections in connection pool (no restrictions with negative values)
spring.redis.pool.max-active=8  
# Maximum blocking waiting time for connection pools (using negative values to indicate no restrictions)
spring.redis.pool.max-wait=-1  
# Maximum idle connection in connection pool
spring.redis.pool.max-idle=8  
# Minimum idle connection in connection pool
spring.redis.pool.min-idle=0  
# Connection timeout time (milliseconds)
spring.redis.timeout=0  

3. Configuration classes for adding cache

@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);
        //Setting cache expiration time
        //Rcm.setDefault Expiration (60);//s
        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. OK, 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("aa@126.com", "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());
    }
}

These are all manual ways to use, how to automatically use the cache when looking up the database, see below;

4. Automatically generate cache according to method

@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
    User user=userRepository.findByUserName("aa");
    System.out.println("If there is no "Call without Cache" below and the data can be printed to indicate the success of the test.");  
    return user;
}

The value of value is the key cached in redis

Sharing Session-spring-session-data-redis

In distributed systems, session sharing has many solutions, among which hosting in cache should be one of the most commonly used.

Official Statement of Spring Session

Spring Session provides an API and implementations for managing a user's session information.

How to use it

1. Introducing Dependence

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

2. Session configuration:

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 86400*30)
public class SessionConfig {
}

maxInactiveIntervalInSeconds: Sets the Session expiration time, and after using Redis Session, the server.session.timeout attribute of the original Boot no longer takes effect.

Okay, that's all configured. Let's test it.

3. Testing

Add test methods to get session ID

@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();
    }

Log in redis and enter keys '*sessions*'

t<spring:session:sessions:db031986-8ecc-48d6-b471-b137a3ed6bc4
t(spring:session:expirations:1472976480000

Among them, 1472976480000 is the expiration time, which means that session fails after this time. db031986-8ecc-48d6-b471-b137a3ed6bc4 is session Id. Log in at http://localhost:8080/uid. Finding consistency indicates that session has been effectively managed in redis.

How to Share Sessions in Two or More Sets

In fact, according to the above steps in another project configuration once again, after the start of session sharing automatically.




Keywords: Redis Session Spring Database

Added by kf on Sat, 13 Jul 2019 03:38:29 +0300