gpt4 book ai didi

redis - Spring Data RedisTemplate,设置值时ttl不起作用

转载 作者:IT王子 更新时间:2023-10-29 05:56:48 28 4
gpt4 key购买 nike

我想为存储在 Redis 中的 key 设置一个 ttl,我是通过以下方式完成的:

@Component
public class RedisBetgeniusMarketService implements BetgeniusMarketService {

private static final int DEFAULT_EVENTS_LIFE_TIME = 240;

@Value("${redis.events.lifetime}")
private long eventsLifeTime = DEFAULT_EVENTS_LIFE_TIME;

@Autowired
private RedisTemplate<String, Market> marketTemplate;

@Override
public Market findOne(Integer fixtureId, Long marketId) {
String key = buildKey(fixtureId, marketId);
return marketTemplate.boundValueOps(key).get();
}

@Override
public void save(Integer fixtureId, Market market) {
String key = buildKey(fixtureId, market.getId());
BoundValueOperations<String, Market> boundValueOperations = marketTemplate.boundValueOps(key);
boundValueOperations.expire(eventsLifeTime, TimeUnit.MINUTES);
boundValueOperations.set(market);
}

private String buildKey(Integer fixtureId, Long marketId) {
return "market:" + fixtureId + ":" + marketId;
}
}

但是,当我打印创建的 key 的 ttl 时,它等于 -1

请告诉我我做错了什么。

模板bean配置如下:

    @Bean
public RedisTemplate<String, com.egalacoral.spark.betsync.entity.Market> marketTemplate(RedisConnectionFactory connectionFactory) {
final RedisTemplate<String, com.egalacoral.spark.betsync.entity.Market> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer(com.egalacoral.spark.betsync.entity.Market.class));
redisTemplate.setConnectionFactory(connectionFactory);
return redisTemplate;
}

最佳答案

您需要以不同的顺序调用 expire(...)set(...)SET命令删除之前应用的任何超时:

来自 http://redis.io/commands/set 处的文档:

Set key to hold the string value. If key already holds a value, it is overwritten, regardless of its type. Any previous time to live associated with the key is discarded on successful SET operation.

在您的情况下,您只需要将 expire(...)set(...) 的顺序切换为 set(...)过期(...)

@Override
public void save(Integer fixtureId, Market market) {
String key = buildKey(fixtureId, market.getId());
BoundValueOperations<String, Market> boundValueOperations = marketTemplate.boundValueOps(key);

boundValueOperations.set(market);
boundValueOperations.expire(eventsLifeTime, TimeUnit.MINUTES);
}

除此之外,您可以通过在一次调用中设置值和到期时间来改进代码。 ValueOperations (RedisOperations.opsForValue()) 提供了一个set方法,通过签名设置key和timeout

void set(K key, V value, long timeout, TimeUnit unit);

关于redis - Spring Data RedisTemplate,设置值时ttl不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38502746/

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