我正在尝试为mongodb中发生的任何更改设置更新缓存机制。为此,我实现了一个侦听器:
@Bean
public MessageListenerContainer messageListenerContainer(MongoTemplate template){
MessageListenerContainer messageListenerContainer = new DefaultMessageListenerContainer(template);
messageListenerContainer.start();
ChangeStreamRequest<BinDataItem> request = ChangeStreamRequest.builder()
.collection("BIN")
.publishTo(getBinListener())
.build();
messageListenerContainer.register(request, BinDataItem.class);
return messageListenerContainer;
}
@Bean
@Qualifier("BinDataUpdateListener")
public BinDataUpdateListener<ChangeStreamDocument<Document>, BinDataItem> getBinListener(){
return new BinDataUpdateListener<ChangeStreamDocument<Document>, BinDataItem>();
}
方法的更新是:
public class BinDataUpdateListener<C, T> implements MessageListener<ChangeStreamDocument<Document>, BinDataItem> {
@Autowired
@Qualifier("binDataLoader")
CacheManager cacheManager;
@Override
public void onMessage(Message<ChangeStreamDocument<Document>, BinDataItem> message) {
BinDataItem binDataItem = (BinDataItem)message.getBody(); // this value comes as null for a delete operation
String operationType = message.getRaw().getOperationType().getValue();
try {
cacheManager.updateCache(operationType, binDataItem, message.getRaw().getDocumentKey());
}
catch(RedisCommandTimeoutException ex){
addToSLogger(DomainConstants.GET_BIN_DATA_STRING, DomainConstants.ERR_CODE_MS1003, ex);
throw ex;
}
catch(RedisBusyException ex){
addToSLogger(DomainConstants.GET_BIN_DATA_STRING, DomainConstants.ERR_CODE_MS1002, ex);
throw ex;
}
catch(RedisConnectionFailureException ex){
addToSLogger(DomainConstants.GET_BIN_DATA_STRING, DomainConstants.ERR_CODE_MS1002, ex);
throw ex;
}
catch(Exception ex){
addToSLogger(DomainConstants.GET_BIN_DATA_STRING, DomainConstants.ERR_CODE_MS1001, ex);
throw ex;
}
}
private void addToSLogger(String messageName, String errorCode, Exception e){
Slogger.get()
.withTag(DomainConstants.MSG_ERROR)
.withField(DomainConstants.MSG_NAME, messageName)
.withField(DomainConstants.ERR_CODE, errorCode)
.withThrowable(e)
.info(e.getMessage());
}
}
bindataitem pojo是:
@Document(collection = "BIN")
@JsonIgnoreProperties(ignoreUnknown=true)
public class BinDataItem implements Serializable {
@BsonProperty(value = "_id")
private String id;
private String bin;
}
问题是,每当发生delete类型的事件时,被删除的对象在程序中都是null。我需要mongo中已删除对象的字段bin来在redis缓存中删除它。我知道如何获取objectid,但其他所有字段我都不知道。
暂无答案!
目前还没有任何答案,快来回答吧!