Spring Data Redis Expire Key Spring Data Redis Expire Key spring spring

Spring Data Redis Expire Key


I am using Spring Data Redis.I am using @Redishash(timeToLive=300) annotation to expire my Entities after 300 seconds.

Here is the excerpt from my pom.xml

......<parent>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-parent</artifactId>    <version>2.1.7.RELEASE</version>    <relativePath /> <!-- lookup parent from repository --></parent>......<dependencies>    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-data-redis</artifactId>    </dependency>    <dependency>        <groupId>redis.clients</groupId>        <artifactId>jedis</artifactId>    </dependency>......

My RedisConfig.class

@Configuration@Log4j2@EnableRedisRepositories(basePackageClasses = ConsentOTP.class)public class RedisConfig {    @Value("${spring.redis.host}")    private String host;    @Value("${spring.redis.port}")    private Integer port;    @Value("${spring.redis.password}")    private String password;    @Bean    JedisConnectionFactory jedisConnectionFactory() {        log.info("=================================================================");        log.info("redis config : {} : {} ", host, port);        log.info("=================================================================");        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);        config.setPassword(RedisPassword.of(password));        return new JedisConnectionFactory(config);    }}

And my entity class ConsentOtp.class

@RedisHash(value = "ConsentOTP", timeToLive = 300)@Data@NoArgsConstructorpublic class ConsentOTP implements Serializable {    private static final long serialVersionUID = 1708925807375596799L;    private String id;    private LocalDateTime timestamp;    private String otp;    public ConsentOTP(String personId, LocalDateTime timestamp, String otp) {        this.id = personId;        this.timestamp = timestamp;        this.otp = otp;    }}

Here is my Redis repository

public interface ConsentOtpRepository extends CrudRepository<ConsentOTP, String> {}


I am using Redis Version 3.2.100.

Instead of redis template ,Use Redis Cache Manager, pass redistemplate to cacheManager and use its set expires property to which is basically map of String & Long , you can add cache name and set its expiry time i.e time to live (TTL).

You can use setDefaultExpiration method of cacheManager to set same expiry time to all the cache.

@SuppressWarnings({ "rawtypes", "unused" })@Configuration@EnableCaching(proxyTargetClass = true, mode = AdviceMode.ASPECTJ, order = 1)@PropertySource("classpath:/application.properties")public class CacheConfigImpl extends CachingConfigurerSupport {    private @Value("${redis.ip}") String redisHost;    private @Value("${redis.port}") int redisPort;     private static final Map<String, Long> cacheMap = new HashMap<String, Long>();    static {        cacheMap.put("method1cache", 600L);        cacheMap.put("method2cache", 600L);        cacheMap.put("method3cache", 800L);    }    @Bean    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {        return new PropertySourcesPlaceholderConfigurer();    }    @Bean    public JedisConnectionFactory redisConnectionFactory() {        JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory();        redisConnectionFactory.setHostName(CustomPropertyLoader.getProperty("redis.ip"));        redisConnectionFactory.setPort(Integer.parseInt(CustomPropertyLoader.getProperty("redis.port")));        return redisConnectionFactory;    }    @Bean    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory redisConnectionFactory) {        RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>();        redisTemplate.setConnectionFactory(redisConnectionFactory);        redisTemplate.afterPropertiesSet();        return redisTemplate;    }    @Bean(name = "RCacheManager")    public CacheManager cacheManager(RedisTemplate redisTemplate) {        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);        cacheManager.setExpires(cacheMap);        cacheManager.setUsePrefix(true);        final String redis_client_name = CustomPropertyLoader.getProperty("redis.client.name");        cacheManager.setCachePrefix(new RedisCachePrefix() {            private final RedisSerializer<String> serializer = new StringRedisSerializer();            private final String delimiter = ":";            public byte[] prefix(String cacheName) {                return this.serializer                        .serialize(redis_client_name.concat(this.delimiter).concat(cacheName).concat(this.delimiter));            }        });        return cacheManager;    }    }


Actually you can do it with Redisson Redis Java Client using RMapCache object. It provides ability to set ttl and maxIdle per map entry. Example:

// implements java.util.concurrent.ConcurrentMap interfaceRMapCache<String, SomeObject> map = redisson.getMapCache("anyMap");// ttl = 10 minutes, map.put("key1", new SomeObject(), 10, TimeUnit.MINUTES);// ttl = 10 minutes, maxIdleTime = 10 secondsmap.put("key1", new SomeObject(), 10, TimeUnit.MINUTES, 10, TimeUnit.SECONDS);