目录

  前言

  生产者和消费者

  发布和订阅

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. iview2.x版本升级3.x版本icon修改清单

    当前公司使用有一个旧项目的前端组件库是iview2.x,入职以来维护该项目过程中碰到2.x版本无数的坑. 最近需求不多,闲来无事把2.x升级到3.x版本了. 新版本除了网上轻易可查到的button组件 ...

  2. 十一.spring-boot 添加http自动转向https

    SSL是为网络通信提供安全以及保证数据完整性的的一种安全协议,SSL在网络传输层对网络连接进行加密. 例:cas 的单点登陆就用到了SSL 一.安全证书的生成 1.可以使用jdk自带的证书生成工具,j ...

  3. 如何查看Oracle日志

    Oracle日志查看 一.Oracle日志的路径: 登录:sqlplus "/as sysdba" 查看路径:SQL> select * from v$logfile; SQ ...

  4. python 协程的学习记录

    协程是个子程序,执行过程中,内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行 从句法上看,协程与生成器类似,都是定义体中包含 yield 关键字的函数.可是,在协程中,yield 通常 ...

  5. request.startAsync()不支持异步操作

    Servlet3.0使用异步处理时,后台报错: java.lang.IllegalStateException: A filter or servlet of the current chain do ...

  6. Maven中setting.xml配置Demo

    <!-- 指定本地默认仓库 --> <localRepository>G:\Java\apache-maven-3.5.2\repository</localReposi ...

  7. .Net Framework 之 框架图

    .Net Framework框架图,如下图:  它表明了这么一种编写软件的方式或者说表明了.Net平台下开发软件的思想和规范. .Net Framework框架实际只包含两部分: 1.公共语言运行时( ...

  8. 新手IOS tweak越狱app开发记录

    需要改变原先程序功能流程的话,是要用到Logos Tweak 开发.另外,.在苹果商城下载到的app,不能直接拿来分析.需要先做一定的前期准备.网上有很多相关的写第一个越狱插件的文章,这里就不在赘言了 ...

  9. Android 8.0新特性-取消大部分静态注册广播

    今天楼主在写一个广播的demo,功能非常的简单,就是一个应用发送一个自定义的广播,同时在这个应用里面定义了一个广播接受者,并且在AndroidManifest文件中进行静态的注册.Demo看上去非常的 ...

  10. Java设计模式(十) 备忘录模式 状态模式

    (十九)备忘录模式 备忘录模式目的是保存一个对象的某个状态,在适当的时候恢复这个对象. class Memento{ private String value; public Memento(Stri ...