skip to Main Content

I use

    @Value("${cache.host}")
    private String redisHost;

    @Value("${cache.port}")
    private int redisPort;

I want to get timeToLive in @RedishHash from application properties. How can get this config?

@RedisHash(value = "UserModel", timeToLive = 5)

I give manually above however I want to give from application.properties

2

Answers


  1. i’m not sure if you can do that from application.properties, but u can do it by configuring a RedisCacheManager bean with java based configuration like below :

    @Bean
    public RedisCacheManager RedisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        Map<String, RedisCacheConfiguration> cacheConfig = new HashMap<String, RedisCacheConfiguration>();
        cacheConfig.put("UserModel", RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofHours(5)));
        RedisCacheManager rdisCacheManager = new RedisCacheManager(
                RedisCacheWriter.lockingRedisCacheWriter(redisConnectionFactory),
                RedisCacheConfiguration.defaultCacheConfig(), cacheConfig);
        return rdisCacheManager;
    }
    

    PS : this method should be in a class with @Configuration annotation

    Login or Signup to reply.
  2. You can create a @Component where you are going to take the values from properties

    @Component
    public class RedisHashCustom {
        private static String redisHashValue;
    
        public static String getRedisHashVaue() {
            return redisHashValue;
        }
    
        @Value("${application.redis.redishash.value}")
        public void setRedisHashValue(String newRedisHashValue) {
            redisHashValue= newRedisHashValue;
        }
    }
    

    Then you need to reference as

    @RedisHash(value = "#{T(com.redis.model.RedisHashCustom).getRedisHashValue() }")
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search