Springboot2 整合 Spring Data Redis 实现消息队列——发布/订阅模式

╰半夏微凉° 2022-09-11 09:23 210阅读 0赞

一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式。

生产者消费者模式:

就像我们用微信和好友(群聊除外)聊天一样,微信就是这个队列,我们可以和很多个好友聊天,但是每条消息只能发给一个好友。

发布者订阅者模式:

发布/订阅模型如图所示,和订阅公众号是一样的。多个消费者可以消费消息。发布者需要建立一个topic 然后消费者去订阅。

接下来用springboot2 + spring data redis 来实现来简单实现订阅者模式:

spring data redis实现发布与订阅需要配置以下信息:

  • - Topic
  • - MessageListener
  • - RedisMessageListenerContainer

1》依赖

  1. <groupId>org.springframework.boot</groupId>
  2. <artifactId>spring-boot-starter-parent</artifactId>
  3. <version>2.5.2</version>
  4. <dependency>
  5. <groupId>org.springframework.boot</groupId>
  6. <artifactId>spring-boot-starter-data-redis</artifactId>
  7. </dependency>
  8. <dependency>
  9. <groupId>com.fasterxml.jackson.core</groupId>
  10. <artifactId>jackson-databind</artifactId>
  11. <version>2.10.0</version>
  12. </dependency>

Spring Boot支持与三种JSON mapping库集成:Gson、Jackson和JSON-B。Jackson是首选和默认的。

Jackson是spring-boot-starter-json的一部分,spring-boot-starter-web中包含spring-boot-starter-json。也就是说,当项目中引入spring-boot-starter-web后会自动引入spring-boot-starter-json。

但因为我这个项目不是web项目 所以还得引入jackson。如果是web项目就不用引入了。

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBA54aZ54aZ5bCP5a2m5aeQ_size_20_color_FFFFFF_t_70_g_se_x_16

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBA54aZ54aZ5bCP5a2m5aeQ_size_20_color_FFFFFF_t_70_g_se_x_16 1

2》配置 spring data redis:

  1. package com.example.messagingredis;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.context.annotation.Bean;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.data.redis.connection.RedisConnectionFactory;
  9. import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import org.springframework.data.redis.listener.ChannelTopic;
  12. import org.springframework.data.redis.listener.RedisMessageListenerContainer;
  13. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  14. import org.springframework.data.redis.serializer.StringRedisSerializer;
  15. @Configuration
  16. public class RedisConfig {
  17. @Autowired
  18. private LettuceConnectionFactory connectionFactory;
  19. @Bean
  20. public ConsumerRedisListener consumeRedis() {
  21. return new ConsumerRedisListener();
  22. }
  23. @Bean
  24. public ChannelTopic topic() {
  25. return new ChannelTopic("topic");
  26. }
  27. @Bean
  28. public RedisMessageListenerContainer redisMessageListenerContainer() {
  29. RedisMessageListenerContainer container = new RedisMessageListenerContainer();
  30. container.setConnectionFactory(connectionFactory);
  31. container.addMessageListener(consumeRedis(), topic());
  32. return container;
  33. }
  34. @Bean
  35. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
  36. RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  37. template.setConnectionFactory(factory);
  38. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
  39. Object.class);
  40. ObjectMapper om = new ObjectMapper();
  41. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  42. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  43. jackson2JsonRedisSerializer.setObjectMapper(om);
  44. template.setValueSerializer(jackson2JsonRedisSerializer);
  45. template.setKeySerializer(new StringRedisSerializer());
  46. template.setHashKeySerializer(new StringRedisSerializer());
  47. template.afterPropertiesSet();
  48. return template;
  49. }
  50. }

3》实现一个pojo 类型的 topic MessageListener :

  1. package com.example.messagingredis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.connection.Message;
  4. import org.springframework.data.redis.connection.MessageListener;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. public class ConsumerRedisListener implements MessageListener {
  7. @Autowired
  8. private RedisTemplate<String, Object> redisTemplate;
  9. @Override
  10. public void onMessage(Message message, byte[] pattern) {
  11. doBusiness(message);
  12. }
  13. /**
  14. * 打印 message body 内容
  15. * @param message
  16. */
  17. public void doBusiness(Message message) {
  18. Object value = redisTemplate.getValueSerializer().deserialize(message.getBody());
  19. System.out.println("consumer message: " + value.toString());
  20. }
  21. }

实体类:

  1. package com.example.messagingredis;
  2. import java.io.Serializable;
  3. public class MessageEntity implements Serializable {
  4. private static final long serialVersionUID = 8632296967087444509L;
  5. private String id;
  6. private String content;
  7. public MessageEntity() {
  8. super();
  9. }
  10. public MessageEntity(String id, String content) {
  11. super();
  12. this.id = id;
  13. this.content = content;
  14. }
  15. public String getId() {
  16. return id;
  17. }
  18. public void setId(String id) {
  19. this.id = id;
  20. }
  21. public String getContent() {
  22. return content;
  23. }
  24. public void setContent(String content) {
  25. this.content = content;
  26. }
  27. @Override
  28. public String toString() {
  29. return "MessageEntity [id=" + id + ", content=" + content + "]";
  30. }
  31. }

4》其它:

记得配置上 redis 相关的配置,最简单的application.properties配置如下:

spring.redis.host=127.0.0.1

spring.redis.port=6379

5》添加测试类:

  1. package com.example.messagingredis;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.context.ApplicationContext;
  5. import org.springframework.data.redis.connection.RedisConnectionFactory;
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import java.util.Date;
  8. @SpringBootApplication
  9. public class MessagingRedisApplication {
  10. public static void main(String[] args) {
  11. ApplicationContext ctx = SpringApplication.run(MessagingRedisApplication.class, args);
  12. RedisConfig template = ctx.getBean(RedisConfig.class);
  13. RedisConnectionFactory factory = null;
  14. RedisTemplate<String,Object> redisTemplate = template.redisTemplate(factory);
  15. String channel = "topic";
  16. redisTemplate.convertAndSend(channel, "hello world");
  17. redisTemplate.convertAndSend(channel, new Date(System.currentTimeMillis()));
  18. redisTemplate.convertAndSend(channel, new MessageEntity("1", "object"));
  19. }
  20. }

执行可以看到控制台有订阅者消费消息打印出来

watermark_type_ZHJvaWRzYW5zZmFsbGJhY2s_shadow_50_text_Q1NETiBA54aZ54aZ5bCP5a2m5aeQ_size_20_color_FFFFFF_t_70_g_se_x_16 2

最后总结下:

用 spring data redis 来实现 redis 订阅者,本质上还是Listener模式,只需要配置Topic, MessageListener 和 RedisMessageListenerContainer就可以了。(就是redisconfig里面的配置)同时,发布时,只需要使用 redisTemplate 的 convertAndSend方法即可topic来发布message。

参考:https://my.oschina.net/simonton/blog/1833775

https://blog.csdn.net/johnf_nash/article/details/87891293

发表评论

表情:
评论列表 (有 0 条评论,210人围观)

还没有评论,来说两句吧...

相关阅读