Use instance of Redis database in Spring Boot

  • 2020-06-19 10:20:51
  • OfStack

spring boot encapsulates and automates nosql database in addition to common database support.

redis introduction

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

How to use

1. Introduce ES27en-ES28en-ES29en-ES30en


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

2. Add configuration files


# REDIS (RedisProperties)
# Redis Database index (default is 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 the connection pool (use negative values to indicate no limit) 
spring.redis.pool.max-active=8 
#  Connection pool maximum blocking wait time (use negative values to indicate no limit) 
spring.redis.pool.max-wait=-1 
#  The maximum free connection in the connection pool 
spring.redis.pool.max-idle=8 
#  Minimum idle connections in the connection pool 
spring.redis.pool.min-idle=0 
#  Connection timeout (in milliseconds) 
spring.redis.timeout=0 

3. Add cache's 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);
    // Sets the cache expiration time 
    //rcm.setDefaultExpiration(60);// seconds 
    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());
  }
}

All of the above are used manually, how to automatically use the cache when looking for the database, see the following;

4. Automatically generate the cache according to the method


@RequestMapping("/getUser")
@Cacheable(value="user-key")
public User getUser() {
  User user=userRepository.findByUserName("aa");
  System.out.println(" If the following does not appear "call without cache" and can print out the data to indicate that the test is successful "); 
  return user;
}

The value of value is key cached in redis

Shared Session spring - session data -- redis

There are many solutions for sessiong sharing in distributed systems, among which hosting into the cache should be one of the most commonly used solutions.

Spring Session Official note

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

How to use

1. Introduce dependencies


<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: Set the expiration time of Session. After using Redis Session, the server.session.timeout attribute of the original Boot will no longer take effect

Okay, so that's all configured, so let's test 1

3, test,

Add a test method to get 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();
  }

Log in to redis input keys '*sessions*'


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

Of which 1472976480000 were failure time, mean session failure after this time, db031986-8 ecc - 48 d6 b471 - b137a3ed6bc4 sessionId, login http: / / localhost: 1, 8080 / uid found means session already in redis for effective management.

How do I share session between two or more platforms

Simply follow the above steps to configure the session again in another project and start it up automatically.


Related articles: