Redis实现延迟消息队列
通过Redis实现消息延迟,下面是DEMO代码
消息类
public class MessNotice {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
Jedis
private Jedis getJedis() {
String password = "redis的密码";
Jedis jedis = new Jedis("127.0.0.1", 6379);
if (password != null && !password.isEmpty()) {
jedis.auth(password);
}
jedis.connect();
return jedis;
}
public Jedis jedis = getJedis();
消息入队,消息出列,消息删除
public static final String DELAY_MESSAGE_QUEUE = "delayQueue";
//消息入队
public static void pushQueue(String id) {
//构造消息对象
MessNotice messNotice = new MessNotice();
messNotice.setId(id);
//序列化
ObjectMapper objectMapper = new ObjectMapper();
try {
String str = objectMapper.writeValueAsString(messNotice);
//发送消息,score延迟1分钟
jedis.zadd(DELAY_MESSAGE_QUEUE,System.currentTimeMillis() + 60000,str);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
//消息出列
public static void pullQueue(String test) {
//读取score在0到当前时间戳之间的消息,每次读取一条数据出来
Set<String> zset = jedis.zrangeByScore(DELAY_MESSAGE_QUEUE, 0, System.currentTimeMillis(), 0, 1);
if (zset.isEmpty()) {
return ;
}
//如果读取到了消息
String next = zset.iterator().next();
//从sort set中移除消息
if (jedis.zrem(DELAY_MESSAGE_QUEUE,next) > 0) {
//抢到了,就在下面处理业务
try {
ObjectMapper objectMapper = new ObjectMapper();
MessNotice messNotice = objectMapper.readValue(next, MessNotice.class);
//testPull为你所需处理的业务
testPull(test, messNotice.getId());
} catch (IOException e) {
e.printStackTrace();
}
}
}
//删除消息
public static void remQueue(String id){
if(!ObjectUtil.isEmpty(jedis.zrank(DELAY_MESSAGE_QUEUE,id))){
jedis.zrem(DELAY_MESSAGE_QUEUE,id);
}
}