使用Redis防止重复发送RabbitMQ消息的方法详解
目录
- 问题
- 方法
- 检验是否已经发送
- 发送后添加缓存
- 发送消息方法
问题
今天遇到一个问题,发送
MQ消息的时候需要保证不会重复发送,注意不是可靠到达(可靠到达可以通过消息确认机制和回调接口保证),这里保证的是不会生产多条一样的消息。方法
综合讨论下来决定使用
Redis缓存来解决,因为相比于将记录插入数据库Redis更为高效和便捷。检验是否已经发送
在发送消息之前根据相关信息组合成
key去Redis中查找,找到后检测值是否为存在并且是否为设定的值,若存在且与设定的值一样,则返回false,说明该消息已经发送过了。 public boolean isSend(String messageType, Long bizId, int hashCode) {
// 根据消息类型、业务id和哈希值组合成key
String key = this.genKey(messageType, bizId, hashCode);
Long value = super.get(key);
if (value != null && value.equals(DEFAULT_VALUE)) {
return false;
}
return true;
}
/**get方法*/
public V get(K key) {
if (key == null) {
return null;
} else {
try {
// 在key前添加前缀和名字,并将原来的key进行json序列化
String realKey = this.genRealKey(key);
String content = (String)this.redisTemplate.opsForValue().get(realKey);
// 若get到的值不为null则进行json反序列化
return content == null ? null : this.valueSerializer.deserialize(content);
} catch (Exception e) {
CACHE.error("", key.toString(), "", "0", e);
return null;
}
}
}