Molay
Molay

Reputation: 1404

Spring Redis - @RedisHash set timeToLive dynamically

I want to set timeToLive value dynamically in RedisHash. i.e., from properties file.

I know @RedisHash is an interface and all the fields are final, we can't assign value dynamically.

@TimeToLive at field level is working fine, but i don't want to create a field to achieve it.

Spring boot version : 2.2.1.RELEASE

@Data
@RedisHash(value = "user", timeToLive = ? ) // what i need to do here to inject dynamically ?
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User implements Serializable {
    @Id
    private String id;
    private String name;
    private String salary;

    //@TimeToLive
    //private long timeToLive; // this is working. But i don't want it like this.
}

Even tried with RedisCacheManager, it's not working. Please suggest if there is any alternative.

@Configuration
@EnableConfigurationProperties(CacheConfigurationProperties.class)
public class CacheConfig extends CachingConfigurerSupport {

    private static RedisCacheConfiguration createCacheConfiguration(long timeoutInSeconds) {
        return RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(timeoutInSeconds));
    }

    @Bean
    public RedisCacheConfiguration cacheConfiguration(CacheConfigurationProperties properties) {
        return createCacheConfiguration(properties.getTimeoutSeconds());
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory, CacheConfigurationProperties properties) {
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();

        for (Map.Entry<String, Long> cacheNameAndTimeout : properties.getCacheExpirations().entrySet()) {
            cacheConfigurations.put(cacheNameAndTimeout.getKey(), createCacheConfiguration(cacheNameAndTimeout.getValue()));
        }

        return RedisCacheManager
                .builder(redisConnectionFactory)
                .cacheDefaults(cacheConfiguration(properties))
                .withInitialCacheConfigurations(cacheConfigurations).build();


    }

Upvotes: 2

Views: 2895

Answers (1)

Juan Delgado
Juan Delgado

Reputation: 51

You can define the following class and define the time in the time field

public class Example implements Serializable {
    private static final long serialVersionUID = 1L;

    private Long id;

    @Indexed
    private String name;

    private String data;

    @TimeToLive
    private long time; --> set time to live
}

Upvotes: 5

Related Questions