本文主要介绍三种实现方式文末有demo链接
-
redis原生消息队列实现 redis版本必须大于5.0
-
redis rightPop实现消息队列
-
reids ZSet实现延迟消息队列
1.redis stream
Redis Stream 是 Redis 5.0 版本新增加的数据结构。
Redis Stream 主要用于消息队列(MQ,Message Queue),Redis 本身是有一个 Redis 发布订阅 (pub/sub) 来实现消息队列的功能,但它有个缺点就是消息无法持久化,如果出现网络断开、Redis 宕机等,消息就会被丢弃。
配置消费者监听
package example.config;
import example.annotation.MeiceRedisStreamListener;
import example.bean.MeiceUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StreamOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.data.redis.stream.StreamListener;
import org.springframework.data.redis.stream.StreamMessageListenerContainer;
import org.springframework.data.redis.stream.Subscription;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;
/**
* 利用redis原生消息队列实现
* Copyright © 2021 meicet. All rights reserved.
* @author zyx
* @date 2021-06-21 09:49:11
*/
@Slf4j
@Configuration
@Component
public class RedisConsumerConfig implements DisposableBean {
@Resource
private ApplicationContext context;
@Resource
private StringRedisTemplate stringRedisTemplate;
private Vector<StreamMessageListenerContainer<String, ObjectRecord<String, MeiceUser>>> containerList = new Vector<>();
@Resource
ForkJoinPool forkJoinPool;
@Resource
RedisConnectionFactory factory;
@Bean(name = "forkJoinPool")
public ExecutorService forkJoinPool() {
return new ForkJoinPool();
}
@PostConstruct
public void initRedisStream() throws Exception {
Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(MeiceRedisStreamListener.class);
if (beansWithAnnotation.size() == 0) {
return;
}
for (Object item : beansWithAnnotation.values()) {
if (!(item instanceof StreamListener)) {
continue;
}
Method method = item.getClass().getDeclaredM