Spring Boot使用Redis进行消息的发布订阅
今天来学习如何利用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进行消息的发布订阅的更多相关文章
- Redis实现消息的发布/订阅
利用spring-boot结合redis进行消息的发布与订阅: 发布: class Publish { private static String topicName = “Topic:chat”; ...
- Spring Data Redis实现消息队列——发布/订阅模式
一般来说,消息队列有两种场景,一种是发布者订阅者模式,一种是生产者消费者模式.利用redis这两种场景的消息队列都能够实现. 定义:生产者消费者模式:生产者生产消息放到队列里,多个消费者同时监听队列, ...
- spring boot: 用redis的消息订阅功能更新应用内的caffeine本地缓存(spring boot 2.3.2)
一,为什么要更新caffeine缓存? 1,caffeine缓存的优点和缺点 生产环境中,caffeine缓存是我们在应用中使用的本地缓存, 它的优势在于存在于应用内,访问速度最快,通常都不到1ms就 ...
- redis实现消息队列&发布/订阅模式使用
在项目中用到了redis作为缓存,再学习了ActiveMq之后想着用redis实现简单的消息队列,下面做记录. Redis的列表类型键可以用来实现队列,并且支持阻塞式读取,可以很容易的实现一个高性 ...
- 【redis】spring boot利用redis的Keyspace Notifications实现消息通知
前言 需求:当redis中的某个key失效的时候,把失效时的value写入数据库. github: https://github.com/vergilyn/RedisSamples 1.修改redis ...
- Spring Boot与Redis的集成
Redis是一个完全开源免费的.遵守BSD协议的.内存中的数据结构存储,它既可以作为数据库,也可以作为缓存和消息代理.因其性能优异等优势,目前已被很多企业所使用,但通常在企业中我们会将其作为缓存来使用 ...
- spring boot 集成 websocket 实现消息主动推送
spring boot 集成 websocket 实现消息主动 前言 http协议是无状态协议,每次请求都不知道前面发生了什么,而且只可以由浏览器端请求服务器端,而不能由服务器去主动通知浏览器端,是单 ...
- 玩转spring boot——结合redis
一.准备工作 下载redis的windows版zip包:https://github.com/MSOpenTech/redis/releases 运行redis-server.exe程序 出现黑色窗口 ...
- 15套java架构师、集群、高可用、高可扩展、高性能、高并发、性能优化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式项目实战视频教程
* { font-family: "Microsoft YaHei" !important } h1 { color: #FF0 } 15套java架构师.集群.高可用.高可扩展. ...
随机推荐
- IIS发布问题-用户 'IIS APPPOOL\DefaultAppPool' 登录失败
今天新建了一个ASP.NET(Language=C#)网站,配置好数据库后编写了几行代码测试数据库的是否能正常使用. 当运行程序时,第一个页面都没有打开就出现了错误(因为我首页就访问数据库,填充一些D ...
- Nutch安装的几个网址
RunNutchInEclipse - Nutch Wiki http://wiki.apache.org/nutch/RunNutchInEclipse Index of /apache/nut ...
- framework层和native层实现联网控制(iptable方式)
最近工作中,需要开发一个功能----联网控制,这个功能其实用过root的安卓机应该都知道,禁止某个应用连接移动网络或者wifi. root后,通过su去执行iptable的命令就可以根据uid去控制应 ...
- fatal error LNK1112: module machine type 'X86' conflicts with target machine type 'x64'
xxxxxx.lib(xxxxxx.obj) : fatal error LNK1112: module machine type 'X86' conflicts with target machin ...
- Hibernate学习之检索策略
一.类级别的检索策略 类级别可选的检索策略包括立即检索和延迟检索, 默认为延迟检索 –立即检索: 立即加载检索方法指定的对象 –延迟检索: 延迟加载检索方法指定的对象,在使用具体的属性时,再进行加载 ...
- ListView 条目加载上滑下滑首尾缩放动画实现
要实现这个效果,只需要再适配器getView之前,给每个条目的view设置相应的动画即可. 首先需要2个动画的xml文件. 在res下新建anim文件夹:(res/anim) 第一个动画xml文件: ...
- java——%
%; //结果为1 %; //结果为-1 ; //结果为1.2000000000000002
- hdu 2565 放大的X
题目: http://acm.hdu.edu.cn/showproblem.php?pid=2565 这个题很简单 但是很容易错,写来给自己一个警示把 首先在最后一个x后面没有空格,然后就是那个换行一 ...
- 8_Times_Tables
8 // // ViewController.swift // Times Tables // // Created by ZC on 16/1/9. // Copyright © 2016年 ZC. ...
- openstack nova修改实例路径,虚拟磁盘路径
#实例路径 --instances_path=$state_path/instances #日志的目录 --logdir=/var/log/nova #nova的目录 --state_path=/va ...