目录

  前言

  生产者和消费者

  发布和订阅

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. 用yum安装完mysql后没有mysqld的问题

    在Centos中用命令 yum install mysql安装数据库,但装完后运行mysqld启动mysql的时候提示找不到,通过 find / | grep mysqld 也没找到mysqld的目录 ...

  2. 一份不太简短的LaTeX教程 lshort – A short in­tro­duc­tion to LATEX 2elshort – A short in­tro­duc­tion to LATEX 2e

    Lshort started as a trans­la­tion and ra­tio­nal­i­sa­tion of a ground-break­ing Ger­man-lan­guage i ...

  3. Javascript中的对象(二)

    Javascript是一种基于原型的对象语言,而不是我们比较熟悉的,像C#语言基于类的面向对象的语言.在前一篇文章中,我们已经介绍了Javascript中对象定义的创建.接下来我们来介绍一下Javas ...

  4. B. Suffix Structures 模拟吧,情况比較多要想周全

    这道题须要考虑的情况比較多,flag1表示情况是:b数组里有的字母而a里没有和b里面的同一个字母个数比a里面的多 flag2表示情况:b里面的左右字母能不能在a中同等顺序的存在 flag3表示情况:a ...

  5. unity3d的矩阵元素存储方式

    想知道u3d矩阵各个元素的存储方式,所以测试了一下 Matrix4x4 m = Matrix4x4.TRS(new Vector3(1, 2, 3), Quaternion.Euler(0, 0, 3 ...

  6. Node & Cheerio & WebStorm 学习实验

    准备用cheerio去抓一些网页看看. 可以参考的材料有: http://www.cnblogs.com/CraryPrimitiveMan/p/3674421.html http://cnodejs ...

  7. zend 环境

    js智能提示: 安装APTANA组件,最新3.0版本 安装地址:http://download.aptana.com/studio3/plugin/install Aptana 3 不能装 2 的 J ...

  8. mac office 设置默认视图显示比例

    1.打开word 2.fn+option+F11,选中Normal,右键插入模块,复制以下脚本到编辑器中 Sub AutoOpen() ActiveWindow.ActivePane.View.Zoo ...

  9. (转)Akka学习笔记

    Akka学习笔记系列文章: <Akka学习笔记:ACTORS介绍> <Akka学习笔记:Actor消息传递(1)> <Akka学习笔记:Actor消息传递(2)> ...

  10. 手写Json转换

    在做项目的时候总是要手动将集合转换成json每次都很麻烦,于是就尝试着写了一个公用的方法,用于转换List to json: using System; using System.Collection ...