Redis key expire with Spring Boot



few weeks ago i got a requirement to temporally store few information of users in a separate database.There can be few users at a time and after few minutes stored data should be terminated automatically. Since its temporaly store and i dont want to make request to add or delete temporary data frequently i checked other options.  After doing few reading i decided to use redis server to store data.

redis is a software project that implements key and value data structure service. It run as a seperate server and you need to provide redis server connection details to store data from your application.
For my requirment i used redis expire. i can set a timeout on key when i store data in redis. When timeout expire redis will delete the key automatically.

There are two options you can use to expire redis key.
1. RedisTemplate.expire method
2. RedisCacheManager.setExpires method

Using RedisTemplate

public void storeValues(){
redisTemplate.opsForValue().set("DataKey", "DataValue");
//Here you can put expiration time
redisTemplate.expire(sessionId, 1, TimeUnit.DAYS);
}

Using  RedisCacheManager

@Bean
public RedisCacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
    RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
    // Open the most key prefix with the cache name
    redisCacheManager.setUsePrefix(true);
    //Here you can set a default expiration time unit in seconds.
    redisCacheManager.setDefaultExpiration(redisDefaultExpiration);

    // Setting the expiration time of the cache
    Map<String, String> expires = new HashMap<>();
    expires.put("DataKey", "DataValue");
    //Here you can put expiration time
    redisCacheManager.setExpires(expires);

    return redisCacheManager;
}

Comments

Popular Posts