【发布时间】:2020-09-19 04:22:32
【问题描述】:
我使用 Spring Data Redis 将购物车存储在 Redis 中特定时间。使用 @TimeToLive 注释的过期属性设置 Cart 对象的生存时间,如下面的代码所述。
我设置了KeyExpirationEventMessageListener 类型来监听过期事件,以便在过期事件中处理额外的工作。我能够从过期对象的触发事件中获取密钥,并且我试图在过期时使用 spring 数据存储库访问它或其幻像对象,但没有结果。它返回一个空对象,这意味着原始对象对象很可能已被删除。我不知道这是否是正确的方法。但是,有没有办法在到期时或在它被删除以处理移动工作之前获取到期对象?
@RedisHash("cart")
public class Cart implements Serializable {
@Id
@Indexed
private String id;
private long customerId;
private Set<CartLine> lines = new HashSet<>();
@TimeToLive
private long expiration;
}
public interface ShoppingCartRepository extends CrudRepository<Cart, String> {
}
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
private RedisTemplate<?, ?> redisTemplate;
private ShoppingCartRepository repository;
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer,
RedisTemplate redisTemplate, ShoppingCartRepository repository) {
super(listenerContainer);
this.redisTemplate = redisTemplate;
this.repository = repository;
}
@Override
public void onMessage(Message message, byte[] pattern) {
String key = new String(message.getBody());
try {
String id = extractId(key);
Optional<ShoppingCart> cart = repository.findById(id);
} catch(Exception e) {
logger.info("something went wrong ====> " + e.getStackTrace());
}
}
private String extractId(String key){
String keyPrefix = ShoppingCart.class.getAnnotation(RedisHash.class).value();
return key.substring((keyPrefix + ":").length());
}
}
【问题讨论】:
标签: spring-boot spring-data spring-data-redis