【Springboot+Redis】Springboot+Redis实现消息队列(生产者/消费者、发布订阅模式)

 

转载自,原文格式清晰:https://blog.csdn.net/niuchenliang524/article/details/81326238

一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式。利用redis这两种场景的消息队列都能够实现。

定义:
        生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列,谁先抢到消息谁就会从队列中取走消息;即对于每个消息只能被最多一个消费者拥有。
        发布者订阅者模式:发布者生产消息放到队列里,多个监听队列的消费者都会收到同一份消息;即正常情况下每个消费者收到的消息应该都是一样的。

Redis不仅可作为缓存服务器,还可用作消息队列。它的列表类型天生支持用作消息队列。如下图所示:

由于Redis的列表是使用双向链表实现的,保存了头尾节点,所以在列表头尾两边插取元素都是非常快的。

在Redis中,List类型是按照插入顺序排序的字符串链表。和数据结构中的普通链表一样,我们可以在其头部(left)和尾部(right)添加新的元素。在插入时,如果该键并不存在,Redis将为该键创建一个新的链表。与此相反,如果链表中所有的元素均被移除,那么该键也将会被从数据库中删除。List中可以包含的最大元素数量是4294967295。
从元素插入和删除的效率视角来看,如果我们是在链表的两头插入或删除元素,这将会是非常高效的操作,即使链表中已经存储了百万条记录,该操作也可以在常量时间内完成。然而需要说明的是,如果元素插入或删除操作是作用于链表中间,那将会是非常低效的。相信对于有良好数据结构基础的开发者而言,这一点并不难理解。

Redis List的主要操作为lpush/lpop/rpush/rpop四种,分别代表从头部和尾部的push/pop,除此之外List还提供了两种pop操作的阻塞版本blpop/brpop,用于阻塞获取一个对象。

Redis通常都被用做一个处理各种后台工作或消息任务的消息服务器。 一个简单的队列模式就是:生产者把消息放入一个列表中,等待消息的消费者用 RPOP 命令(用轮询方式), 或者用 BRPOP 命令(如果客户端使用阻塞操作会更好)来得到这个消息。

1、Redis 生产者/消费者模式实现消息队列的简单例子(此外用的是jedisCluster连接redis)

springboot的application-dev.yml中redis的配置如下:


  
  
  1. redis:
  2.     database: 0
  3.     password: # Redis服务器连接密码(默认为空)
  4.     timeout: 0 # 连接超时时间(毫秒)
  5.     commandTimeout: 5000
  6.     cluster:
  7.         nodes: 10.201.1.27: 7001, 10.201.1.27: 7002, 10.201.1.27: 7003, 10.201.1.27: 7004, 10.201.1.27: 7005, 10.201.1.27: 7006

redis放入Spring容器中:


  
  
  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import redis.clients.jedis.HostAndPort;
  5. import redis.clients.jedis.JedisCluster;
  6. import java.util.HashSet;
  7. import java.util.Set;
  8. @Configuration
  9. public class RedisHostsConfig {
  10.     @Value( "${spring.redis.cluster.nodes}")
  11.     private String hosts;
  12. /**
  13. * 获取jedis链接
  14. * @return
  15. */
  16. @Bean
  17. public JedisCluster redisCluster(){
  18.     try{
  19.         Set<HostAndPort> nodes = new HashSet<>();
  20.         String[] hostArray = hosts.split( ",");
  21.         for(String host : hostArray){
  22.             String[] ipAndPort = host.split( ":");
  23.             nodes.add( new HostAndPort(ipAndPort[ 0], Integer.parseInt(ipAndPort[ 1])));
  24.         }
  25.         JedisCluster cluster = new JedisCluster(nodes);
  26.         return cluster;
  27.     } catch(Exception e){
  28.         e.printStackTrace();
  29.         return null;
  30.     }
  31. }
  32. }

 

生产者代码:


  
  
  1. public class RedisProducer {
  2.     @Autowired
  3.     JedisCluster jedisCluster;
  4.     public static void main(String[] args){
  5.         for( int i = 0;i< 10;i++) {
  6.             jedisCluster.lpush( "listingList", "value_" + i);  
  7.         }
  8.     }
  9.  
  10. }

 


  
  
  1. import lombok.extern.slf4j.Slf4j;
  2. import redis.clients.jedis.JedisCluster;
  3. import java.util.List;
  4. @Slf4j
  5. public class NetListingConsumer extends Thread {
  6.     private static JedisCluster redisCluster;
  7.     private static JedisCluster getRedisCluster(){
  8.         if (redisCluster == null){
  9.             redisCluster = SpringContextHolder.getBean( "redisCluster");
  10.         }
  11.         return redisCluster;
  12.     }
  13.     @Override
  14.     public void run() {
  15.         JedisCluster redis = getRedisCluster();
  16.         while ( true){
  17.             //阻塞式brpop,List中无数据时阻塞,参数0表示一直阻塞下去,直到List出现数据
  18.             List<String> listingList = redis.brpop( 0, "listingList");
  19.             log.info( "线程取数据:{}", listingList.get( 1));
  20.         }
  21.     }
  22. }

 

消费者代码:

运行消费者:


  
  
  1. public class RedisProducer {
  2.      public static void main(String[] args){
  3.         PriceConsumer redisConsumer = new PriceConsumer();
  4.         redisConsumer.start();
  5.     }
  6. }


spring-redis使用RedisMessageListenerContainer进行消息监听,客户程序需要自己实现MessageListener,并以指定的topic注册到RedisMessageListenerContainer,这样,在指定的topic上如果有消息,RedisMessageListenerContainer便会通知该MessageListener。2、Redis 发布/订阅模式实现消息队列的简单例子(此外用的是redisTemplater操作redis)

在此,我是监听了四个topic,为每一个topic写了一个消息处理方法。


  
  
  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.data.redis.connection.RedisConnectionFactory;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.data.redis.listener.PatternTopic;
  9. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  10. import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12. import java.util.concurrent.CountDownLatch;
  13. @Configuration
  14. public class RedisMessageListener {
  15. /**
  16. * redis消息监听器容器
  17. * @param connectionFactory
  18. * @param priceListenerAdapter 价格趋势和市场消息订阅处理器
  19. * @param listingListenerAdapter 挂牌案例消息订阅处理器
  20. * @param caseListenerAdapter 交易案例消息订阅处理器
  21. * @param foreclosureListenerAdapter 法拍案例消息订阅处理器
  22. * @return
  23. */
  24. @Bean
  25. RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
  26.                 MessageListenerAdapter priceListenerAdapter,
  27.                 MessageListenerAdapter listingListenerAdapter,
  28.                 MessageListenerAdapter caseListenerAdapter,
  29.                 MessageListenerAdapter foreclosureListenerAdapter) {
  30.     RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  31.     container.setConnectionFactory(connectionFactory);
  32.     //监听价格趋势和市场情况主题并绑定消息订阅处理器
  33.     container.addMessageListener(priceListenerAdapter, new PatternTopic( "PRICE_TOPIC"));
  34.     //监听挂牌案例主题并绑定消息订阅处理器
  35.     container.addMessageListener(listingListenerAdapter, new PatternTopic( "LISTING_TOPIC"));
  36.     //监听交易案例主题并绑定消息订阅处理器
  37.     container.addMessageListener(caseListenerAdapter, new PatternTopic( "CASE_TOPIC"));
  38.     //监听法拍案例主题并绑定消息订阅处理器
  39.     container.addMessageListener(foreclosureListenerAdapter, new PatternTopic( "FORECLOSURE_TOPIC"));
  40.     return container;
  41. }
  42. /**
  43. * 价格趋势和市场消息订阅处理器,并指定处理方法
  44. * @param receiver
  45. * @return
  46. */
  47. @Bean
  48. MessageListenerAdapter priceListenerAdapter(ReceiverRedisMessage receiver) {
  49.     MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "priceReceive");
  50.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jacksonSerializer();
  51.     messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
  52.     return messageListenerAdapter;
  53. }
  54. /**
  55. * 挂牌案例消息订阅处理器,并指定处理方法
  56. * @param receiver
  57. * @return
  58. */
  59. @Bean
  60. MessageListenerAdapter listingListenerAdapter(ReceiverRedisMessage receiver) {
  61.     MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "listingReceive");
  62.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jacksonSerializer();
  63.     messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
  64.     return messageListenerAdapter;
  65. }
  66. /**
  67. * 交易案例消息订阅处理器,并指定处理方法
  68. * @param receiver
  69. * @return
  70. */
  71. @Bean
  72. MessageListenerAdapter caseListenerAdapter(ReceiverRedisMessage receiver) {
  73.     MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "caseReceive");
  74.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jacksonSerializer();
  75.     messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
  76.     return messageListenerAdapter;
  77. }
  78. /**
  79. * 法拍案例消息订阅处理器,并指定处理方法
  80. * @param receiver
  81. * @return
  82. */
  83. @Bean
  84. MessageListenerAdapter foreclosureListenerAdapter(ReceiverRedisMessage receiver) {
  85.     MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(receiver, "foreclosureReceive");
  86.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = this.jacksonSerializer();
  87.     messageListenerAdapter.setSerializer(jackson2JsonRedisSerializer);
  88.     return messageListenerAdapter;
  89. }
  90. @Bean
  91. ReceiverRedisMessage receiver(CountDownLatch latch) {
  92.     return new ReceiverRedisMessage(latch);
  93. }
  94. @Bean
  95. CountDownLatch latch() {
  96.     return new CountDownLatch( 1);
  97. }
  98. @Bean
  99. RedisTemplate template(RedisTemplate redisTemplate) {
  100.     return redisTemplate;
  101. }
  102. private Jackson2JsonRedisSerializer jacksonSerializer(){
  103.     Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  104.     ObjectMapper objectMapper = new ObjectMapper();
  105.     objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  106.     objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  107.     jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
  108.     return jackson2JsonRedisSerializer;
  109. }
  110. }
 

 


  
  
  1. import com.alibaba.fastjson.JSON;
  2. import com.cindata.esp.domian.casehistory.CaseHistory;
  3. import com.cindata.esp.domian.foreclosure.ForeclosureHistory;
  4. import com.cindata.esp.domian.netlisting.NetListingHistory;
  5. import com.cindata.esp.domian.pricetendency.PriceTendencySituation;
  6. import com.cindata.esp.service.ICaseService;
  7. import com.cindata.esp.service.IForeclosureService;
  8. import com.cindata.esp.service.INetListingService;
  9. import com.cindata.esp.service.IPirceTendencyService;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import java.util.concurrent.CountDownLatch;
  13. @Slf4j
  14. public class ReceiverRedisMessage {
  15.     private CountDownLatch latch;
  16.     @Autowired
  17.     IPirceTendencyService priceTendencyService;
  18.     @Autowired
  19.     INetListingService netListingService;
  20.     @Autowired
  21.     ICaseService caseService;
  22.     @Autowired
  23.     IForeclosureService foreclosureService;
  24.     @Autowired
  25.     public ReceiverRedisMessage(CountDownLatch latch) {
  26.         this.latch = latch;
  27.     }
  28. /**
  29. * 价格趋势和市场队列消息接收方法
  30. * @param jsonMsg
  31. */
  32. public void priceReceive( String jsonMsg) {
  33.     log.info( "[开始消费REDIS消息队列PRICE_TOPIC数据...]");
  34.     try{
  35.         PriceTendencySituation priceTendencySituation = JSON.parseObject(jsonMsg, PriceTendencySituation.class);
  36.         priceTendencyService.save(priceTendencySituation);
  37.         log.info( "[消费REDIS消息队列PRICE_TOPIC数据成功.]");
  38.     } catch(Exception e){
  39.         log.error( "[消费REDIS消息队列PRICE_TOPIC数据失败,失败信息:{}]", e.getMessage());
  40.     }
  41.     latch.countDown();
  42. }
  43. /**
  44. * 挂牌案例队列消息接收方法
  45. * @param jsonMsg
  46. */
  47. public void listingReceive( String jsonMsg) {
  48.     log.info( "[开始消费REDIS消息队列LISTING_TOPIC数据...]");
  49.     try{
  50.         NetListingHistory netListingHistory = JSON.parseObject(jsonMsg, NetListingHistory.class);
  51.         netListingService.save(netListingHistory);
  52.         log.info( "[消费REDIS消息队列LISTING_TOPIC数据成功.]");
  53.     } catch(Exception e){
  54.         log.error( "[消费REDIS消息队列LISTING_TOPIC数据失败,失败信息:{}]", e.getMessage());
  55.     }
  56.     latch.countDown();
  57. }
  58. /**
  59. * 交易案例队列消息接收方法
  60. * @param jsonMsg
  61. */
  62. public void caseReceive( String jsonMsg) {
  63.     log.info( "[开始消费REDIS消息队列CASE_TOPIC数据...]");
  64.     try{
  65.         CaseHistory caseHistory = JSON.parseObject(jsonMsg, CaseHistory.class);
  66.         caseService.save(caseHistory);
  67.         log.info( "[消费REDIS消息队列CASE_TOPIC数据成功.]");
  68.     } catch(Exception e){
  69.         log.error( "[消费REDIS消息队列CASE_TOPIC数据失败,失败信息:{}]", e.getMessage());
  70.     }
  71.     latch.countDown();
  72. }
  73. /**
  74. * 法拍案例队列消息接收方法
  75. * @param jsonMsg
  76. */
  77. public void foreclosureReceive( String jsonMsg) {
  78.     log.info( "[开始消费REDIS消息队列FORECLOSURE_TOPIC数据...]");
  79.     try{
  80.         ForeclosureHistory foreclosureHistory = JSON.parseObject(jsonMsg, ForeclosureHistory.class);
  81.         foreclosureService.save(foreclosureHistory);
  82.         log.info( "[消费REDIS消息队列FORECLOSURE_TOPIC数据成功.]");
  83.     } catch(Exception e){
  84.         log.error( "[消费REDIS消息队列FORECLOSURE_TOPIC数据失败,失败信息:{}]", e.getMessage());
  85.     }
  86.     latch.countDown();
  87. }
  88. }

这样,应用启动时,消息的订阅方(subscriber)就注册好了。这时候只要使用一个简单的程序,模拟publisher,向指定topic发布消息,RedisMessageListener就可以接收到消息,spring-redis的写法是这样:

redisTemplate.convertAndSend("PRICE_TOPIC", "hello world!");

发布订阅模式,在集群化部署时会重复消费数据,暂时还没找到一个类似消费kafka数据手工维护偏移量的方法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值