今天来学习如何利用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. 使用泛型对java数组扩容

    编写一个通用方法,其功能是将数组扩展到10%+10个元素(转载请注明出处) package cn.reflection; import java.lang.reflect.Array; public ...

  2. trangle

    #include<iostream> #include<algorithm> using namespace std; int main() { int a,b,c; whil ...

  3. 数据库分页【Limt与Limt..OFFSET 】

    数据起始 SELECT * from xiaoyao_blogs_essay  limit 20 , 15;解释:20是起始位置,15是页容量.因为id是从15开始的 SELECT * from xi ...

  4. QTreeView处理大量数据(使用1000万条数据,每次都只是部分刷新)

    如何使QTreeView快速显示1000万条数据,并且内存占用量少呢?这个问题困扰我很久,在网上找了好多相关资料,都没有找到合理的解决方案,今天在这里把我的解决方案提供给朋友们,供大家相互学习. 我开 ...

  5. qt5集成libcurl实现tftp和ftp的方法一:搭建环境(五篇文章)

    最近使用QT5做一个软件,要求实现tftp和ftp文件传输,使用QT5开发好UI界面等功能,突然发现QT5不直接提供tftp和ftp支持,无奈之下只好找第三方库来间接实现,根据网友的介绍,libcur ...

  6. Html 小插件3

    搜狗搜索框代码 <script>function verifyquery(form){if(form.sogou_drop.value==2){form.insite.value='';} ...

  7. easyui-layout中的收缩层无法显示标题问题解决

    先看问题描述效果图片: 如上,我的查询条件是放在layout下面的一个可收缩层中,初始是收缩的,title显示不出来的话对使用者很不方便,代码如下: <div id="__MODULE ...

  8. 脑波设备mindwave二次开发框架

    神念科技提供的mindwave提供了脑波耳机和相应的游戏,这些游戏你可以通过购买神念科技的mindwave耳机来获取,这里不多作介绍. 我们作为程序员,如果有了相应的创意,也可以通过他们提供的二次开发 ...

  9. Codeforces Beta Round #97 (Div. 2)

    A题求给出映射的反射,水题 #include <cstdio> int x,ans[105],n; int main(){ scanf("%d",&n); fo ...

  10. PHP批量下载方法

      PHP批量下载方法 界面: $.get(“< ?php echo url::base(true);?>inventory/report/buildCsv”, //后台路径 {‘para ...