目录

  前言

  生产者和消费者

  发布和订阅

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)的更多相关文章

  1. Redis_发布订阅(基础)

    目录 前言 生产者和消费者 发布和订阅 Java实现 注意 前言 随着业务复杂, 业务的项目依赖关系增强, 使用消息队列帮助系统降低耦合度.发布订阅(pub/sub)是一种消息通信模式,主要目的是解除 ...

  2. Spring Boot 1.5.10 发布:修复重要安全漏洞!!!

    2018/01/31,Spring Boot团队发布了Spring Boot 1.5.10. Maven: <parent> <groupId>org.springframew ...

  3. 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个错误修复.文档改进和依赖项升级). 这两个版本均为缺陷修复版本 ...

  4. 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基线从 ...

  5. 三万字盘点Spring/Boot的那些常用扩展点

    大家好,我是三友. Spring对于每个Java后端程序员来说肯定不陌生,日常开发和面试必备的.本文就来盘点Spring/SpringBoot常见的扩展点,同时也来看看常见的开源框架是如何基于这些扩展 ...

  6. 使用Spring Boot快速构建应用

    http://www.infoq.com/cn/news/2014/01/spring-boot/ 随着Spring 4新版本的发布,Spring Boot这个新的子项目得到了广泛的关注,因为不管是S ...

  7. Spring Boot整合Spring Security

    Spring Boot对于该家族的框架支持良好,但是当中本人作为小白配置还是有一点点的小问题,这里分享一下.这个项目是使用之前发布的Spring Boot会员管理系统重新改装,将之前filter登录验 ...

  8. 《深入实践Spring Boot》阅读笔记之一:基础应用开发

    上上篇「1718总结与计划」中提到,18年要对部分项目拆分,进行服务化,并对代码进行重构.公司技术委员会也推荐使用spring boot,之前在各个技术网站中也了解过,它可以大大简化spring配置和 ...

  9. 一文读懂 Spring Boot、微服务架构和大数据治理三者之间的故事

    微服务架构 微服务的诞生并非偶然,它是在互联网高速发展,技术日新月异的变化以及传统架构无法适应快速变化等多重因素的推动下诞生的产物.互联网时代的产品通常有两类特点:需求变化快和用户群体庞大,在这种情况 ...

随机推荐

  1. Linux(CentOS)下squid代理服务器配置-五岳之巅

    squid是linux下的一款代理服务器软件,他可以共享网络 ,加快访问速度,节约通信带宽,同时防止内部主机受到攻击,限制用户访问,完善网络管理 rpm -qa|grep squidyum insta ...

  2. Email the output of a concurrent program as Attachment

    This article illustrates the steps to be followed to Email a concurrent program's output. Write a pr ...

  3. 利用谷歌API生成二维码

    http://chart.apis.google.com/chart?cht=qr&chs=104x104&chld=L|0&chl=http://www.cnblogs.co ...

  4. Oracle SQL执行缓慢的原因以及解决方案

     以下的文章抓哟是对Oracle SQL执行缓慢的原因的分析,如果Oracle数据库中的某张表的相关数据已是2亿多时,同时此表也创建了相关的4个独立的相关索引.由于业务方面的需要,每天需分两次向此表中 ...

  5. 用latex写毕业论文

    用 LaTeX 写漂亮学位论文(from wloo) 序 一直觉得有必要写这样一篇文章,因为学位论文从格式上说更像一本书,与文章 的排版不同,不仅多出目录等文章没有的部分,而且一般要设置页眉页脚方便阅 ...

  6. Linux系统443端口被占用无法启动解决办法

    etstat -ano|findstr "443"         //搜索443端口占用情况,并找到进程IDTCP 0.0.0.0:443 0.0.0.0:0 LISTENING ...

  7. Hibernate连接MySQL

    1 下载hibernate-3.6.0 Final.zip到任意目录,解压缩后得到hibernate目录 2 下载slf4j-1.7.13.zip到任意目录,解压缩后得到slf4j-1.7.13 3  ...

  8. .NET dnSpy 程序集编辑器,反编译器和调试器

    https://github.com/0xd4d/dnSpy https://github.com/0xd4d/dnSpy/releases/ dnSpy是反向工程.NET程序集的工具.它包括一个反编 ...

  9. 图解aclocal、autoconf、automake、autoheader、configure

    http://www.laruence.com/2008/11/11/606.html 本文地址: http://www.laruence.com/2008/11/11/606.html 转载文章 原 ...

  10. ASPCMS不能上传2M以上大文件修改!

    \admin_aspcms\editor\upload.asp修改80行左右maxattachsize=xxxxxxxx'最大上传大小,默认是2M前提是IIS上传大小已修 其他有关IIS方面的修改: ...