如何在Spring Boot从application.properties中获取Redis哈希配置,如Time to L



我使用

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

我想从应用程序属性中获取@RedishHash中的timeToLive。如何获取此配置?

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

我在上面手动给出,但我想从application.properties 中给出

我不确定你是否可以从application.properties中做到这一点,但你可以通过使用基于java的配置来配置RedisCacheManagerbean来做到这一步,如下所示:

@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:这个方法应该在一个带有@Configuration annotation 的类中

您可以创建一个@Component,从属性中获取值

@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;
}
}

然后你需要参考

@RedisHash(value = "#{T(com.redis.model.RedisHashCustom).getRedisHashValue() }")

最新更新