gpt4 book ai didi

Spring Redis - @RedisHash 动态设置 timeToLive

转载 作者:行者123 更新时间:2023-12-02 19:46:20 27 4
gpt4 key购买 nike

我想在 RedisHash 中动态设置 timeToLive 值。即来自属性文件。

我知道@RedisHash是一个接口(interface),所有字段都是最终的,我们无法动态赋值。

@TimeToLive 在字段级别工作正常,但我不想创建一个字段来实现它。

Spring 启动版本: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.
}

即使尝试使用RedisCacheManager,它也不起作用。请建议是否有任何替代方案。

@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();


}

最佳答案

您可以定义以下类并在时间字段中定义时间

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
}

关于Spring Redis - @RedisHash 动态设置 timeToLive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59179063/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com