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、微服务架构和大数据治理三者之间的故事
微服务架构 微服务的诞生并非偶然,它是在互联网高速发展,技术日新月异的变化以及传统架构无法适应快速变化等多重因素的推动下诞生的产物.互联网时代的产品通常有两类特点:需求变化快和用户群体庞大,在这种情况 ...
随机推荐
- TJSONTableObject跨平台解析JSON
TJSONTableObject跨平台解析JSON USES SynCrossPlatformJSON TSQLRecordPeoplePersistent = class(TPersistent) ...
- Go -- php 中的pack("H*", $string) 转换成go
pack("H*", $string) 转化成这样: //16进制字符串转[]byte func HexToByte(hex string) []byte { length := ...
- 翻译:Spring-Framework-Reference Document:15.2-DispatcherServlet
写在前面的话: 最近被项目的代码折腾的死去活来的,其实框架也没有那么难理解,只是自己的Web基础太差,被Request和Response这一对神雕侠侣坑到泪流满面!今天捣腾了一下Spring We ...
- Kubernetes下的应用监控解决方案
所谓应用监控,更多的是基于java jvm的监控,因为公司运行的中间件大部分都是基于tomcat,Springboot,SpringCloud,当然也必须支持WebLogic.在Kubernetes现 ...
- [转]Understanding Integration Services Package Configurations
本文转自:http://msdn.microsoft.com/en-us/library/cc895212.aspx Introduction With the 2008 release, SQL S ...
- Vue打包项目图片等静态资源的处理
项目打包,默认是打包在根目录下面的.当然我们可以通过设置,打包到任意子目录中去. 但是,当项目中引入资源的,比如:引入图片资源.js资源.或者字体图标之类的.那么可能在这个中间又会踩坑. 1.在vue ...
- myEclipse的配置
- 说说C#之父——安德斯·海尔斯伯格
安德斯·海尔斯伯格(Anders Hejlsberg,1960.12~),丹麦人,Turbo Pascal编译器的主要作者,Delphi和.NET之父! 看到照片的那一刹那儿,我就觉得帅爆了,53岁的 ...
- ssl证书之certbot
一.安装 1.下载压缩包:#wget https://github.com/certbot/certbot/archive/master.zip 2.解压包 3.官方文档https://github. ...
- taro + taro-ui + dva
taro的安装及使用 安装 Taro 开发工具 @tarojs/cli 使用 npm 或者 yarn 全局安装,或者直接使用npx $ npm install -g @tarojs/cli $ yar ...