• SpringBoot中使用redis发布订阅的学习


    1、引入POM文件:

     1 <dependency>
     2     <groupId>org.springframework.boot</groupId>
     3     <artifactId>spring-boot-starter-web</artifactId>
     4 </dependency>
     5 <dependency>
     6     <groupId>org.springframework.boot</groupId>
     7     <artifactId>spring-boot-starter-web</artifactId>
     8 </dependency>
     9 <dependency>
    10     <groupId>org.springframework.boot</groupId>
    11     <artifactId>spring-boot-starter-data-redis</artifactId>
    12 </dependency>

    2、Redis配置(在application.yml文件中配置):

    1 spring:
    2     redis:
    3         database: 0   # Redis数据库索引(默认为0)
    4         host: localhost  # Redis服务器地址
    5         port: 6379  # Redis服务器连接端口
    6         password:    # Redis服务器连接密码(默认为空)
    7         timeout: 5000  # 连接超时时间(毫秒)

    3、实现消息生产者:

     1 @RestController
     2 public class SampleController {
     3 
     4     @Autowired
     5     private RedisTemplate<String, String> redisTemplate;
     6 
     7     @GetMapping(value = "/send1")
     8     public String send1(String message) {
     9         redisTemplate.convertAndSend("TextChannel", message);
    10         return "send1 success";
    11     }
    12 
    13     @GetMapping(value = "send2")
    14     public String send2(String message) {
    15         redisTemplate.convertAndSend("kafkaChannel", message);
    16         return "send2 success";
    17     }
    18 }

    4、实现消息消费者:

    1 @Component
    2 public class RedisSubscriber extends MessageListenerAdapter {
    3 
    4     @Override
    5     public void onMessage(Message message, byte[] pattern) {
    6         System.out.println(message);
    7     }
    8 }

    5、配置消费者连接的Bean

    1 @Bean
    2 public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
    3                                                MessageListenerAdapter listenerAdapter) {
    4     RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    5     container.setConnectionFactory(connectionFactory);
    6     container.addMessageListener(listenerAdapter, new PatternTopic("TextChannel"));
    7     container.addMessageListener(listenerAdapter, new PatternTopic("kafkaChannel"));//配置要订阅的订阅项
    8     return container;
    9 }

    6、测试:

    http://localhost:8080/send1?message=111111
    http://localhost:8080/send2?message=2222222
  • 相关阅读:
    YII2中andWhere多个or查询
    PHP中使用date获取上月最后一天出现的问题
    使用PHP生成并导出CSV文件
    如何开启MySQL慢查询日志
    PHP使用递归按层级查找数据
    PHP设计模式之单例模式
    Yii2中多表关联查询
    剑指Offer_编程题_合并两个排序的链表
    剑指Offer_编程题_反转链表
    Java自带的性能监测工具_jstack
  • 原文地址:https://www.cnblogs.com/laoxia/p/11759226.html
Copyright © 2020-2023  润新知