我希望存储在 redis 缓存中的数据在给定时间段后自动从缓存中清除,而不对其调用 delete 方法。在这个 POC 中,我将 TTL 设置为 60 秒。我尝试使用 API setDefaultExpiration、setExpires 在缓存管理器中设置它,并使用 API expires 在 RedisTemplate 中设置它。到目前为止,没有一个解决方案对我有用。
@Configuration
public class RedisServerConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(connectionFactory());
redisTemplate.setKeySerializer(new StringRedisSerializer());
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String, String> redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
redisCacheManager.setUsePrefix(true);
redisCacheManager.setCacheNames(cacheNames);
redisCacheManager.setTransactionAware(true);
redisCacheManager.setLoadRemoteCachesOnStartup(true);
// Using setDefaultExpiration
//redisCacheManager.setDefaultExpiration(60);
// Using setExpires
//Map<String, Long> expires = new HashMap<>();
//cacheNames.stream().forEach(name->expires.put(name, 60L));
//redisCacheManager.setExpires(expires);
return redisCacheManager;
}
@Bean
public RedisConnectionFactory connectionFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setTestOnBorrow(true);
poolConfig.setTestOnReturn(true);
poolConfig.setTestWhileIdle(true);
poolConfig.setMaxWaitMillis(secondsToWait);
JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfig(), poolConfig);
factory.setUsePool(true);
factory.setPassword(redisPassword);
factory.setPort(redisPort);
return factory;
}
}
在使用的redis仓库中,
@Repository
public class RedisRepository {
private static final Logger logger = LoggerFactory.getLogger(RedisRepositoryImpl.class);
@Autowired
private RedisTemplate<String, String> redisTemplate;
public void saveSharedSecret(String customerNumber, String sharedSecret) {
redisTemplate.opsForHash().put(MfaConstants.REDIS_SHAREDSECRET_REGION, myKey, myValue);
redisTemplate.expire(myKey, 1, TimeUnit.MINUTES);
// The timeOut obtained here is zero
logger.info("myKey: [{}], timeOut: [{}]", myKey, redisTemplate.getExpire(myKey, TimeUnit.SECONDS));
}
}
请指出我正确的方向。任何帮助表示赞赏。