SpringBoot集成Redis并使用Redis发布订阅模式

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介: SpringBoot集成Redis并使用Redis发布订阅模式

1.概念

Redis的发布订阅模式是一种消息通信机制,其中发布者(Publisher)可以向一个或多个订阅者(Subscriber)发送消息。订阅者可以订阅一个或多个主题,以便只接收与这些主题相关的消息。

2.组成

发布订阅模式中,通常有以下几个组件:

  1. 发布者(Publisher):负责向一个或多个订阅者发送消息。
  2. 订阅者(Subscriber):订阅一个或多个主题,并接收与这些主题相关的消息。
  3. 消息主题(Topic):用于区分不同类型的消息。

当发布者发送消息时,该消息会被发送到相应的主题。然后,订阅了该主题的订阅者会接收到该消息。

这就像是一个发布/订阅关系,发布者发布消息,订阅者订阅主题并接收消息。

3.集成

spring:
  profiles:
    active: dev
  redis:
    host: 127.0.0.1
    port: 6379
    password:
 <dependency>
                <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>provided</scope>
        </dependency>
 
     
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

4.单一主题

package com.lp.redis;
 
 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:05
 * @Description:
 */
@Configuration
public class RedisConfig {
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisMessageListener listener) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        //订阅频道redis.news 和 redis.life  这个container 可以添加多个 messageListener
        container.addMessageListener(listener, new ChannelTopic("redis.life"));
        container.addMessageListener(listener, new ChannelTopic("redis.news"));
        return container;
    }
 
    
 
   
   
}
package com.lp.redis;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:01
 * @Description: 这个在其他项目实现就可以
 */
@Component
public class RedisMessageListener implements MessageListener {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 获取消息
        byte[] messageBody = message.getBody();
        // 使用值序列化器转换
        Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
        // 获取监听的频道
        byte[] channelByte = message.getChannel();
        // 使用字符串序列化器转换
        Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
        // 渠道名称转换
        String patternStr = new String(pattern);
        System.out.println(patternStr);
        System.out.println("---频道---: " + channel);
        System.out.println("---消息内容---: " + msg);
    }
}
package com.lp.redis;
 
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:07
 * @Description:
 */
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class TestDemo {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    public void publish() {
        // 使用convertAndSend方法向频道redisChat发布消息
        redisTemplate.convertAndSend("redis.life", "aaa");
        redisTemplate.convertAndSend("redis.news", "bbb");
        redisTemplate.convertAndSend("test.news", "ccc");
    }
}

5.模糊匹配多个主题

package com.lp.redis.redis;
 
import org.springframework.stereotype.Component;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:29
 * @Description:
 */
 
@Component
public class MessageReceiver {
    public void receiveMessage(String message,String channel){
        System.out.println("MessageReceiver ---频道---: " + channel);
        System.out.println("MessageReceiver ---消息内容---: " + message);
    }
}
package com.lp.redis;
 
import com.lp.redis.redis.MessageReceiver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:05
 * @Description:
 */
@Configuration
public class RedisConfig {
    
 
    /**
     * 订阅所有 redis.开头多个频道
     */
    @Bean
    public PatternTopic patternTopic() {
        return new PatternTopic("redis.*");
    }
 
    @Bean
    public MessageListenerAdapter listenerAdapter(MessageReceiver receiver) {
        return new MessageListenerAdapter(receiver, "receiveMessage");
    }
 
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory factory, MessageListenerAdapter adapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(factory);
        // 一次订阅多个匹配的频道
        container.addMessageListener(adapter, patternTopic());
        return container;
    }
}
package com.lp.redis;
 
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
 
/**
 * @author liu pei
 * @date 2023年12月13日 下午7:07
 * @Description:
 */
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class TestDemo {
 
    @Autowired
    private RedisTemplate redisTemplate;
 
    @Test
    public void publish() {
        // 使用convertAndSend方法向频道redisChat发布消息
        redisTemplate.convertAndSend("redis.life", "aaa");
        redisTemplate.convertAndSend("redis.news", "bbb");
        redisTemplate.convertAndSend("test.news", "ccc");
    }
}
相关文章
|
存储 缓存 NoSQL
深入理解Django与Redis的集成实践
深入理解Django与Redis的集成实践
430 0
|
2月前
|
人工智能 安全 数据库
构建可扩展的 AI 应用:LangChain 与 MCP 服务的集成模式
本文以LangChain和文件系统服务器为例,详细介绍了MCP的配置、工具创建及调用流程,展现了其“即插即用”的模块化优势,为构建复杂AI应用提供了强大支持。
|
8月前
|
NoSQL Java 关系型数据库
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
本文介绍在 Spring Boot 中集成 Redis 的方法。Redis 是一种支持多种数据结构的非关系型数据库(NoSQL),具备高并发、高性能和灵活扩展的特点,适用于缓存、实时数据分析等场景。其数据以键值对形式存储,支持字符串、哈希、列表、集合等类型。通过将 Redis 与 Mysql 集群结合使用,可实现数据同步,提升系统稳定性。例如,在网站架构中优先从 Redis 获取数据,故障时回退至 Mysql,确保服务不中断。
339 0
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 介绍
|
2月前
|
监控 Cloud Native Java
Spring Integration 企业集成模式技术详解与实践指南
本文档全面介绍 Spring Integration 框架的核心概念、架构设计和实际应用。作为 Spring 生态系统中的企业集成解决方案,Spring Integration 基于著名的 Enterprise Integration Patterns(EIP)提供了轻量级的消息驱动架构。本文将深入探讨其消息通道、端点、过滤器、转换器等核心组件,以及如何构建可靠的企业集成解决方案。
249 0
|
4月前
|
测试技术 API C++
Playwright 自动化测试系列(7)| 第三阶段:测试框架集成​​Page Object 模式
本课程详解Playwright测试框架中的Page Object模式,通过电商登录-下单实战演示PO架构设计与高级技巧,结合Pytest实现多用户测试。重点解析PO模式提升代码复用性、降低维护成本的核心价值,并提供常见问题解决方案,助力构建高可维护性的自动化测试体系。
|
10月前
|
负载均衡 IDE Java
SpringBoot整合XXL-JOB【04】- 以GLUE模式运行与执行器负载均衡策略
在本节中,我们将介绍XXL-JOB的GLUE模式和集群模式下的路由策略。GLUE模式允许直接在线上改造方法为定时任务,无需重新部署。通过一个测试方法,展示了如何在调度中心配置并使用GLUE模式执行定时任务。接着,我们探讨了多实例环境下的负载均衡策略,确保任务不会重复执行,并可通过修改路由策略(如轮训)实现任务在多个实例间的均衡分配。最后,总结了GLUE模式和负载均衡策略的应用,帮助读者更深入理解XXL-JOB的使用。
538 9
SpringBoot整合XXL-JOB【04】-  以GLUE模式运行与执行器负载均衡策略
|
8月前
|
NoSQL Java API
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Spring Boot 集成 Redis
本文介绍了在Spring Boot中集成Redis的方法,包括依赖导入、Redis配置及常用API的使用。通过导入`spring-boot-starter-data-redis`依赖和配置`application.yml`文件,可轻松实现Redis集成。文中详细讲解了StringRedisTemplate的使用,适用于字符串操作,并结合FastJSON将实体类转换为JSON存储。还展示了Redis的string、hash和list类型的操作示例。最后总结了Redis在缓存和高并发场景中的应用价值,并提供课程源代码下载链接。
1991 0
|
8月前
|
NoSQL Java Redis
微服务——SpringBoot使用归纳——Spring Boot 中集成Redis——Redis 安装
本教程介绍在 VMware 虚拟机(CentOS 7)或阿里云服务器中安装 Redis 的过程,包括安装 gcc 编译环境、下载 Redis(官网或 wget)、解压安装、修改配置文件(如 bind、daemonize、requirepass 等设置)、启动 Redis 服务及测试客户端连接。通过 set 和 get 命令验证安装是否成功。适用于初学者快速上手 Redis 部署。
233 0
|
12月前
|
消息中间件 监控 Java
您是否已集成 Spring Boot 与 ActiveMQ?
您是否已集成 Spring Boot 与 ActiveMQ?
372 0
|
存储 SQL 消息中间件
springboot整合redis
redis是一个支持key-value的数据库,数据全部在内存中处理,在在一定时间间隔中将数据固化到磁盘。因为是内存操作,所以速度特别快。(这里我们主要介绍redis作为缓存使用)
303 0
springboot整合redis
下一篇
oss云网关配置