今天来学习如何利用Spring Data对Redis的支持来实现消息的发布订阅机制。发布订阅是一种典型的异步通信模型,可以让消息的发布者和订阅者充分解耦。在我们的例子中,我们将使用StringRedisTemplate来发布一个字符串消息,同时基于MessageListenerAdapter使用一个POJO来订阅和响应该消息。

提示

事实上,RedisRedis 不仅提供一个NoSQL数据库,同时提供了一套消息系统。

环境准备

开发环境:

  • IDE+Java环境(JDK 1.7或以上版本)
  • Maven 3.0+(Eclipse和Idea IntelliJ内置,如果使用IDE并且不使用命令行工具可以不安装)

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.tianmaing</groupId>
<artifactId>redis-message</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>redis-message</name>
<description>Demo of message processing by redis</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.5.RELEASE</version>
<relativePath/>
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

通过配置spring-boot-starter-redis依赖,把Spring Boot对Redis的相关支持引入进来。

创建Redis消息的接收者

在任何一个基于消息的应用中,都有消息发布者和消息接收者(或者称为消息订阅者)。创建消息的接收者,我们只需一个普通POJO,在POJO中定义一个接收消息的方法即可:

package com.tianmaying.springboot.redisdemo;

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类将会被注册为一个消息监听者时。处理消息的方法我们可以任意命名,我们有相当大的灵活性。

我们给Receiver的构造函数通过@AutoWired标注注入了一个CountDownLatch实例,当接收到消息时,调用cutDown()方法。

注册监听者和发送消息

Spring Data Redis提供基于Redis发送和接收消息的所有需要的组件,我们只需要配置好三个东西:

  • 一个连接工厂(connection factory)
  • 一个消息监听者容器(message listener container)
  • 一个Redis的模板(redis template)

我们将通过Redis模板来发送消息,同时将Receiver注册给消息监听者容器。连接工厂将两者连接起来,使得它们可以通过Redis服务器通信。如何连接呢? 我们将连接工厂实例分别注入到监听者容器和Redis模板中即可。

package com.tianmaying.springboot.redisdemo;

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; @SpringBootApplication
public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); @Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container;
} @Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
} @Bean
Receiver receiver(CountDownLatch latch) {
return new Receiver(latch);
} @Bean
CountDownLatch latch() {
return new CountDownLatch(1);
} @Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
} public static void main(String[] args) throws InterruptedException { ApplicationContext ctx = SpringApplication.run(App.class, args); StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
CountDownLatch latch = ctx.getBean(CountDownLatch.class); LOGGER.info("Sending message...");
template.convertAndSend("chat", "Hello from Redis!"); latch.await(); System.exit(0);
}
}

连接工程我们使用Spring Boot默认的RedisConnectionFactory,是Jedis Redis库提供的JedisConnectionFactory实现。

我们将在listenerAdapter方法中定义的Bean注册为一个消息监听者,它将监听chat主题的消息。

因为Receiver类是一个POJO,要将它包装在一个消息监听者适配器(实现了MessageListener接口),这样才能被监听者容器RedisMessageListenerContainer的addMessageListener方法添加到连接工厂中。有了这个适配器,当一个消息到达时,就会调用receiveMesage()`方法进行响应。

就这么简单,配置好连接工厂和消息监听者容器,你就可以监听消息啦!

发送消息就更简单了,我们使用StringRedisTemplate来发送键和值均为字符串的消息。在main()方法中我们创建一个Spring应用的Context,初始化消息监听者容器,开始监听消息。然后获取StringRedisTemplate的实例,往chat主题发送一个消息。我们看到,消息可以被成功的接收到并打印出来,搞定!

Spring Boot使用Redis进行消息的发布订阅的更多相关文章

  1. Redis实现消息的发布/订阅

    利用spring-boot结合redis进行消息的发布与订阅: 发布: class Publish { private static String topicName = “Topic:chat”; ...

  2. Spring Data Redis实现消息队列——发布/订阅模式

    一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现. 定义:生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...

  3. spring boot: 用redis的消息订阅功能更新应用内的caffeine本地缓存(spring boot 2.3.2)

    一,为什么要更新caffeine缓存? 1,caffeine缓存的优点和缺点 生产环境中,caffeine缓存是我们在应用中使用的本地缓存, 它的优势在于存在于应用内,访问速度最快,通常都不到1ms就 ...

  4. redis实现消息队列&发布/订阅模式使用

    在项目中用到了redis作为缓存,再学习了ActiveMq之后想着用redis实现简单的消息队列,下面做记录.   Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易的实现一个高性 ...

  5. 【redis】spring boot利用redis的Keyspace Notifications实现消息通知

    前言 需求:当redis中的某个key失效的时候,把失效时的value写入数据库. github: https://github.com/vergilyn/RedisSamples 1.修改redis ...

  6. Spring Boot与Redis的集成

    Redis是一个完全开源免费的.遵守BSD协议的.内存中的数据结构存储,它既可以作为数据库,也可以作为缓存和消息代理.因其性能优异等优势,目前已被很多企业所使用,但通常在企业中我们会将其作为缓存来使用 ...

  7. spring boot 集成 websocket 实现消息主动推送

    spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...

  8. 玩转spring boot——结合redis

    一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...

  9. 15套java架构师、集群、高可用、高可扩展、高性能、高并发、性能优化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战视频教程

    * { font-family: "Microsoft YaHei" !important } h1 { color: #FF0 } 15套java架构师.集群.高可用.高可扩展. ...

随机推荐

  1. SQL练习之不反复执行相同的计算

    下面是Demo所需要的代码: CREATE TABLE Fee ( Income ,), overhead ,) ) ,) ,) ,) ,) ,) ,) 现在有一个报表系统,需要根据Fee表获得以下数 ...

  2. 配置tomcat的https通信(单向认证)

    1.首先用jdk带的工具生成证书库 打开cmd命令行窗口,cd 到tomcat安装目录的bin下面执行 keytool -v -genkey -alias tomcat -keyalg RSA -ke ...

  3. 思考----拒绝单纯copy

    工作4个多月以来感触最深的是: 做事情的时候遇到不会的可以上网查或者问别人,但是获取到的知识不能只是单纯的copy过来使用达到要求就ok, 更重要的是事后等有空了一定要仔细研究学习,使知识网络完整,这 ...

  4. hdu3507

    题意: 给n(n<=10^6)个非负数字,放在一个数组num中,再给一个特殊值m.求将这个数组分成任意多个区间,每个区间[a,b]的值定义为( sigma(num[i] | (a<=i&l ...

  5. leetcode String to Integer (atoi) python

    class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int "& ...

  6. js函数绑定同时,如何保留代码执行环境?

    经常写js的程序员一定不会对下面这段代码感到陌生. var EventUtil = { addHandler : function(element, type, handler){ if(elemen ...

  7. 去掉iphone 的圆角样式

    每次面对iphone这种丑丑的样式,我简直不能再愉快的写代码~~而且每次记不住那烦人的属性~~~必须记录下来~~ -webkit-appearance:none 为了下次不用再百度,终于背下来~~~

  8. iOS 使用xib创建cell的两种初始化方式

    曾几何时,被自己坑过,为了防止下次继续被自己坑,我决定了!在每个我能看到的地方,都把问题写一遍!!! 方法一: ? 1 2 3 4 第一步: [self.collectionView register ...

  9. Eclipse中搭建Python开发环境

    转载:http://www.cnblogs.com/realh/archive/2010/10/04/1841907.html Eclipse+PyDev环境搭建 1.准备工作 JDK6 Java 开 ...

  10. 如何取消一个本地svn目录与svn的联系(即恢复原有图标等)

    在使用svn 的时候容易手抖错选update地址,使其目录所有同级文件夹上出现蓝色“?”图样,非常烦人,下面记录一下解决方案. 首先在该目录下打开同级文件件,工具→文件夹选项→查看→隐藏文件和文件夹→ ...