如何从application.yml读取Long类型值配置@RedisHash的timeToLive参数
@RedisHash 动态读取配置文件TTL的正确实现方案
错误原因
@RedisHash 注解的属性属于Java注解的静态元数据,属性值必须是编译期可确定的常量,本身不支持解析Spring的${}配置占位符、#{}SpEL表达式。你传入的表达式会被识别为普通字符串,自然无法转换为Long类型的timeToLive参数。
正确实现方式
方案1:全局Keyspace配置(推荐)
通过自定义Redis Keyspace配置统一为指定Hash实体设置TTL,配置值直接从配置文件读取:
- 确保
application.yml配置正确:
throttle: cache: rate: 60
- 新增Redis配置类,自定义
KeyspaceConfiguration:
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.core.convert.KeyspaceConfiguration; import org.springframework.data.redis.core.convert.KeyspaceSettings; import java.util.Collections; @Configuration public class RedisTTLConfig { // 读取配置值,默认值设为60兜底 @Value("${throttle.cache.rate:60}") private long cacheTTL; @Bean public KeyspaceConfiguration keyspaceConfiguration() { return new KeyspaceConfiguration() { @Override protected Iterable<KeyspaceSettings> initialConfiguration() { // 替换为你自己的RedisHash实体类、对应keyspace名称 KeyspaceSettings settings = new KeyspaceSettings(YourHashEntity.class, "your_keyspace_name"); settings.setTimeToLive(cacheTTL); return Collections.singletonList(settings); } }; } }
- 实体类的
@RedisHash注解可以删除timeToLive参数:
@RedisHash("your_keyspace_name") public class YourHashEntity { // 实体字段、业务逻辑 }
方案2:实体类@TimeToLive字段注入
如果仅需要为单个实体独立配置TTL,可以通过@TimeToLive注解绑定配置值:
import org.springframework.beans.factory.annotation.Value; import org.springframework.data.redis.core.TimeToLive; import org.springframework.data.redis.core.RedisHash; import org.springframework.stereotype.Component; import java.util.concurrent.TimeUnit; @Component @RedisHash("your_keyspace_name") public class YourHashEntity { private static Long ttl; // 注入配置值到静态字段 @Value("${throttle.cache.rate:60}") public void setTtl(Long ttl) { YourHashEntity.ttl = ttl; } // 标注为TTL字段,时间单位可自行调整 @TimeToLive(unit = TimeUnit.SECONDS) public Long getTtl() { return ttl; } // 其他实体字段、get/set方法 }
内容的提问来源于stack exchange,提问作者Anton Cavanaugh
相关产品推荐
相关产品推荐

