redis的发布订阅模式,ubuntu命令行demo以及springboot下使用spring-data-redis进行发布订阅

110 篇文章 2 订阅
26 篇文章 1 订阅

我们平时用的rabbitMq和kafka消息都可以实现这种发布订阅模式,但是其实redis也可以实现

在这里插入图片描述

在ubuntu中用命令行演示下发布订阅

订阅 test 频道
在这里插入图片描述
我这里是用docker部署的redis
docker exec -it redis bash登录进redis
然后在/usr/local/bin路径下redis-cli -p 6379新建连接

SUBSCRIBE test
也订阅test这个频道

再同样新建2个连接,发送消息的时候可以看到2个订阅的连接都接收到了消息(前面我单开一个连接的时候自己测试了一下,所以有几条信息没对上不要慌,可以自己试着操作一下)
在这里插入图片描述

订阅收到的消息解释:

  • message代表返回值的类型
  • test就是代表来自哪个频道了
  • is test2和is test 3就是消息的内容了

在这里插入图片描述
在这里插入图片描述

springboot整合redis实现订阅发布

首选上一波官方文档

https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#pubsub

我这里直接使用了spring-data

上依赖,我用的maven,gradle的大家可以自行去mavenRepository里捞

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

application.yml中关于redis的连接配置大家可以自己配置

消息监听处理类
很简洁,可以在自理

package com.chan.wechatshop.service.redis;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

public class RedisTestListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] bytes) {
        System.out.println("订阅者接收到了信息:"+message.toString());
    }
}

绑定消息处理和监听频道

这里把消息处理的类利用@Bean自己手动加载到spring中,然后把业务servicelei利用spring的容器ApplicationContext的getBean方法注入进去,这样就可以在里面进行业务操作了

package com.chan.wechatshop.service.redis;

import com.chan.wechatshop.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.ApplicationContext;
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.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
@EnableCaching
public class RedisListenerConfig extends CachingConfigurerSupport {

    @Autowired
    private ApplicationContext context;


    /**
     * redis消息监听器容器
     * 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     *
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter redisTestListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫 test 的通道
        container.addMessageListener(redisTestListenerAdapter, new PatternTopic("test"));
        //这个container 可以添加多个 messageListener
        return container;
    }

/*  //如果有多个要订阅的频道
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter redisTestListenerAdapter,
                                            MessageListenerAdapter redisTestListenerAdapter2)) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫 test 的通道
        container.addMessageListener(redisTestListenerAdapter, new PatternTopic("test"));
        //订阅了一个叫 test2 的通道
        container.addMessageListener(redisTestListenerAdapter2, new PatternTopic("test2"));
        //这个container 可以添加多个 messageListener
        return container;
    }*/

    @Bean
    MessageListenerAdapter redisTestListenerAdapter(@Qualifier(value = "redisTestListener") RedisTestListener redisTestListener) {
        return new MessageListenerAdapter(redisTestListener);
    }

    @Bean
    RedisTestListener redisTestListener(){
        RedisTestListener redisTestListener = new RedisTestListener();
        ProductServiceImpl productService = context.getBean(ProductServiceImpl.class);
        redisTestListener.setProductService(productService);
        return redisTestListener;
    }

}

发布消息,我这里用的spring-data-redis里的StringRedisTemplate

package com.chan.wechatshop.service.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("redisTest")
@RestController
public class RedisSubscribeControllrt {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("test")
    public String test (@RequestParam("message") String message){
        stringRedisTemplate.convertAndSend("test",message);
        return message;
    }

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
spring-boot-starter-data-redis是Spring Boot提供的用于集成Redis的starter包。它简化了在Spring Boot项目中集成Redis的配置和使用过程。下面是一个简单的演示: 1. 首先,在pom.xml文件中添加spring-boot-starter-data-redis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.properties或application.yml文件中配置Redis连接信息: ```yaml spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 创建一个RedisTemplate bean来操作Redis: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; @Component public class RedisExample { @Autowired private RedisTemplate<String, String> redisTemplate; public void setValue(String key, String value) { redisTemplate.opsForValue().set(key, value); } public String getValue(String key) { return redisTemplate.opsForValue().get(key); } } ``` 4. 在需要使用Redis的地方注入RedisExample bean,并使用它来操作Redis: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class ExampleController { @Autowired private RedisExample redisExample; @GetMapping("/redis/{key}") public String getValue(@PathVariable String key) { return redisExample.getValue(key); } @GetMapping("/redis/{key}/{value}") public void setValue(@PathVariable String key, @PathVariable String value) { redisExample.setValue(key, value); } } ``` 以上演示了如何在Spring Boot项目中集成spring-boot-starter-data-redis,并使用RedisTemplate来操作Redis。你可以根据自己的需求进行进一步的配置和使用

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值