前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【附源码】SpringBoot集成Redis消息订阅发布

【附源码】SpringBoot集成Redis消息订阅发布

作者头像
用户5224393
发布2019-08-13 15:59:39
7980
发布2019-08-13 15:59:39
举报
文章被收录于专栏:Java研发军团
代码语言:javascript
复制
原文地址:https://blog.csdn.net/mynameissls/article/details/75471012#comments

1. pom.xml文件添加依赖

代码语言:javascript
复制
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2. 创建一个Redis消息接收器

代码语言:javascript
复制
package cn.tyrone.springboot.redis.message;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class Receiver {
  private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
  private CountDownLatch latch;
  @Autowired
  public Receiver(CountDownLatch latch) {
    this.latch = latch;
  }

  public void receiveMessage(String message) {
    LOGGER.info("Received <" + message + ">");
    latch.countDown();
  }
}

Receiver这是一个定义了一个接收消息的方法的类。当你把这个类作为一个消息监听器来注册后,你可以自定义消息接收的方法名。本例中采用“receiveMessage”作为接收消息的方法。

3. 注册一个监听器并发送消息

Spring Data Redis 提供了使用Redis发送和接收的消息的所有的组件。我们只需要做以下配置:

一个Redis连接工厂(A connection factory)

一个消息监听器的容器(A message listener container)

一个Redis模板(A redis template)

我们使用redis template发送消息,把Receiver类注册为一个消息监听器以使它可以接收消息。Connection factory是授权它们连接Redis服务的。

本例中采用的是SpringBoot默认的RedisConnectionFactory,这是一个基于jedis Redis库的JedisConnectionFactory的实例。它被注入到消息监听器和redis模板中。

编写SpringBoot启动类并注入本例需要的对象实例

代码语言:javascript
复制
package cn.tyrone.springboot.redis.message;
import java.util.concurrent.CountDownLatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
//https://spring.io/guides/gs/messaging-redis/
@SpringBootApplication
public class Application {
  public static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
  /*
   * Redis消息监听器容器
   * 这个容器加载了RedisConnectionFactory和消息监听器
   */
  @Bean
  RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, 
      MessageListenerAdapter listenerAdapter){
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.addMessageListener(listenerAdapter, new PatternTopic("sprinboot-redis-messaage"));
    return container;
  }
  
  /*
   * 将Receiver注册为一个消息监听器,并指定消息接收的方法(receiveMessage)
   * 如果不指定消息接收的方法,消息监听器会默认的寻找Receiver中的handleMessage这个方法作为消息接收的方法
   */
  @Bean
  MessageListenerAdapter listenerAdapter(Receiver receiver){
    return new MessageListenerAdapter(receiver, "receiveMessage");
  }
  
  /*
   * Receiver实例
   */
  @Bean
  Receiver receiver(CountDownLatch latch){
    return new Receiver(latch);
  }
  
  @Bean
  CountDownLatch latch(){
    return new CountDownLatch(1);
  }
  
  /*
   * Redis Template 用来发送消息
   */
  @Bean
  StringRedisTemplate template(RedisConnectionFactory connectionFactory){
    return new StringRedisTemplate(connectionFactory);
  }
  
  /*
   * 测试用例
   */
  public static void main(String[] args) throws Exception {
    ApplicationContext ctx = SpringApplication.run(Application.class, args);
    
    StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
//    CountDownLatch latch = ctx.getBean(CountDownLatch.class);
    
    LOGGER.info("Sending message......");
    template.convertAndSend("sprinboot-redis-messaage", "Hello, SpringBoot redis message!!!!");
//    latch.wait();
    
    System.exit(0);
    
  }
  
}

对于本例并不十分清楚CountDownLatch latch这个的目的,在测试的过程中,加上这句代码,会抛一个异常,但是发送和接收消息都是成功的。异常信息如下:

代码语言:javascript
复制
2017-07-20 10:14:50.909  INFO 7200 --- [           main] c.t.s.redis.message.Application          : Sending message......
Exception in thread "main" java.lang.IllegalMonitorStateException
  at java.lang.Object.wait(Native Method)
  at java.lang.Object.wait(Object.java:502)
  at cn.tyrone.springboot.redis.message.Application.main(Application.java:77)

如果将此代码注释掉,该异常也将消息。同时,也并不影响消息的发布与接收。CountDownLatch 只是一个同步的辅助类,测试过程中,并没有发现这个类对测试结果的有什么帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-11-22,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Java研发军团 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. pom.xml文件添加依赖
  • 2. 创建一个Redis消息接收器
  • 3. 注册一个监听器并发送消息
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档