Redis_发布订阅(Spring Boot)
目录
前言
生产者和消费者
发布和订阅
Java实现
注意
转至 http://www.tianmaying.com/tutorial/springboot-redis-message
前言
利用Spring Data对Redis的支持来实现消息的发布订阅机制。
使用StringRedisTemplate来发布一个字符串消息,同时基于MessageListenerAdapter使用一个POJO来订阅和响应该消息。
Receiver类将会被注册为一个消息监听者时。给Receiver的构造函数通过@AutoWired标注注入了一个CountDownLatch实例,当接收到消息时,调用cutDown()方法。
Spring Data Redis提供基于Redis发送和接收消息的所有需要的组件,需要配置如下:
a.一个连接工厂(connection factory)
b.一个消息监听者容器(message listener container)
c.一个Redis的模板(redis template)
d.将Receiver注册给消息监听者容器。连接工厂将两者连接起来,使得它们可以通过Redis服务器通信。
实现
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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
application.properties
#spring.redis.database=0
spring.redis.host=192.168.1.10
#spring.redis.password= Login password of the redis server.
#spring.redis.pool.max-active=8
#spring.redis.pool.max-idle=8
#spring.redis.pool.max-wait=-1
#spring.redis.pool.min-idle=0
spring.redis.port=6379
#spring.redis.sentinel.master= Name of Redis server.
#spring.redis.sentinel.nodes= Comma-separated list of host:port pairs.
#spring.redis.timeout=0
Receiver.java
package com.dengzy.springboot.redis; 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 + ">");
//当接收到消息时,调用cutDown()方法。
latch.countDown();
}
}
app.java
package com.dengzy.springboot;
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; import com.dengzy.springboot.redis.Receiver; @SpringBootApplication
public class App { private static final Logger LOGGER = LoggerFactory.getLogger(App.class); //listenerAdapter方法中定义的Bean注册为一个消息监听者,它将监听chat主题的消息。
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) { RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat")); return container;
}
//MessageListenerAdapter使用一个POJO来订阅和响应该消息。
@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);
}
//StringRedisTemplate来发送键和值均为字符串的消息。
@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);
}
}
sendMsg.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; public class SendMessage {
private static Logger logger = LoggerFactory.getLogger(SendMessage.class); public static final String CHANNEL_NAME = "chat"; public static void main(String[] args) throws Exception { JedisPoolConfig poolConfig = new JedisPoolConfig(); JedisPool jedisPool = new JedisPool(poolConfig, "192.168.1.10", 6379, 0); for(int i=0;i<10;i++){
try {
jedisPool.getResource().publish(CHANNEL_NAME, "hello" + i);
} catch (Exception e) {
logger.error("Subscribing failed." + e.getMessage());
}
} }
}
Redis_发布订阅(Spring Boot)的更多相关文章
- Redis_发布订阅(基础)
目录 前言 生产者和消费者 发布和订阅 Java实现 注意 前言 随着业务复杂, 业务的项目依赖关系增强, 使用消息队列帮助系统降低耦合度.发布订阅(pub/sub)是一种消息通信模式,主要目的是解除 ...
- Spring Boot 1.5.10 发布:修复重要安全漏洞!!!
2018/01/31,Spring Boot团队发布了Spring Boot 1.5.10. Maven: <parent> <groupId>org.springframew ...
- Spring Boot发布2.6.2、2.5.8:升级log4j2到2.17.0
12月22日,Spring官方发布了Spring Boot 2.5.8(包括46个错误修复.文档改进和依赖项升级)和2.6.2(包括55个错误修复.文档改进和依赖项升级). 这两个版本均为缺陷修复版本 ...
- Spring Boot 3.0.0 发布第一个里程碑版本M1,你的 Java 升到17 了吗?
2022年1月20日,Spring官方发布了Spring Boot 3.0.0的第一个里程碑版本M1. 下面一起来来看看Spring Boot 3.0.0 M1版本都有哪些重大变化: Java基线从 ...
- 三万字盘点Spring/Boot的那些常用扩展点
大家好,我是三友. Spring对于每个Java后端程序员来说肯定不陌生,日常开发和面试必备的.本文就来盘点Spring/SpringBoot常见的扩展点,同时也来看看常见的开源框架是如何基于这些扩展 ...
- 使用Spring Boot快速构建应用
http://www.infoq.com/cn/news/2014/01/spring-boot/ 随着Spring 4新版本的发布,Spring Boot这个新的子项目得到了广泛的关注,因为不管是S ...
- Spring Boot整合Spring Security
Spring Boot对于该家族的框架支持良好,但是当中本人作为小白配置还是有一点点的小问题,这里分享一下.这个项目是使用之前发布的Spring Boot会员管理系统重新改装,将之前filter登录验 ...
- 《深入实践Spring Boot》阅读笔记之一:基础应用开发
上上篇「1718总结与计划」中提到,18年要对部分项目拆分,进行服务化,并对代码进行重构.公司技术委员会也推荐使用spring boot,之前在各个技术网站中也了解过,它可以大大简化spring配置和 ...
- 一文读懂 Spring Boot、微服务架构和大数据治理三者之间的故事
微服务架构 微服务的诞生并非偶然,它是在互联网高速发展,技术日新月异的变化以及传统架构无法适应快速变化等多重因素的推动下诞生的产物.互联网时代的产品通常有两类特点:需求变化快和用户群体庞大,在这种情况 ...
随机推荐
- std::string 用法
string类的构造函数:string(const char *s); //用c字符串s初始化string(int n,char c); //用n个字符c初始化 string类的字符操作:const ...
- iOS:UIView、UIControl、UIButton、UILabel简单的属性和方法常识
常见属性和方法 一 .UIVIew 常见属性 1.frame 位置和尺寸(以父控件的左上角为原点(0,0)) 2.center 中点 (以父控件的左上角为原点(0,0)) 3.bounds 位置和尺寸 ...
- 如何访问python类中的私有方法
在python中,不像c#/java类语言,支持类的私有方法,这点有点像objc,虽然objc可以通过扩展extension来实现,但源于objc的运行时特性,我们还是可以通过非常手段来进行访问的.不 ...
- npm显示已安装的包
npm list -g --depth 0 显示安装过的npm包!
- 服务器提交了协议冲突. Section=ResponseHeader Detail=CR...的解决方案总结
今天在HttpWebRequest发送一个网页请求的时候,HttpWebResponse返回了一个奇怪的错误信息: 这个Http协议请求类可是微软封装的,我使用的流程可是中规中矩,不可能是我写错代码, ...
- 【MVC5】使用域用户登录+记住我
1.配置Web.config文件 添加域链接字符串 <connectionStrings> <add name="ADConnectionString" conn ...
- Tomcat性能调整完整教程
Tomcat性能调整完整教程 发表于:2007-07-13来源:作者:点击数:526 标签: 一. 引言 性能测试与分析是软件 开发 过程中介于架构和调整的一个广泛并比较不容易理解的领域,更是一项较为 ...
- eclipse下的tomcat内存设置大小(转)
步骤: 1.点击Run 2.选择Run Configurations, 3.系统弹出设置tomcat配置页面,在Argument中末尾添加参数中的VM arguments中追加: -Xms256M - ...
- 在项目中增加自定义icon图标
以MUI框架为例,内容来自于MUI官网. mui如何增加自定义icon图标 mui框架遵循极简原则,在icon图标集上也是如此,mui仅集成了原生系统中最常用的图标:其次,mui中的图标并不是图片,而 ...
- 在需要隐藏navigationController控制器
- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationControll ...