介绍

  • 当初做消息推送的时候考虑了websocket跟redis两个方案
  • 虽然最终选择了websocket,但是redis的demo我也做了
  • 现在把他封装了下,下次可以快速的使用

    引入依赖

    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-test</artifactId>
    8. <scope>test</scope>
    9. </dependency>
    10. <!-- redis - push -->
    11. <dependency>
    12. <groupId>cn.jdevelops</groupId>
    13. <artifactId>caches-redis-pub</artifactId>
    14. <version>2.0.3</version>
    15. </dependency>

    开始配置

  • 默认配置了两个频道

  • 默认配置本机redis (保证redis正常运行且没有密码)
  • 如果要用自己的频道和修改默认连接请在 application.properties 添加以下配置 ```yaml jdevelops: redis: cache:
    1. pub:
    2. pattern-topic: # 频道名
    3. - test
    4. - tn
    spring: redis: database: 1 host: 127.0.0.1 port: 6379 timeout: 2000

spring.redis.database=1

spring.redis.host=192.168.2.3

spring.redis.port=6379

spring.redis.password=

spring.redis.timeout=2000

#

debug=false

#

订阅发布的频道

tn.redis.cache.subpub.pattern-topic[0]=test

tn.redis.cache.subpub.pattern-topic[1]=test

  1. <a name="YqswM"></a>
  2. # 示例测试
  3. <a name="6e5JG"></a>
  4. ## 观测
  5. - 打开redis管理端(命令行)输入命令 `SUBSCRIBE 频道名`
  6. - 默认频道有两个: test, tn
  7. - 调用接口
  8. ```java
  9. package com.example.redis.pub.controller;
  10. import com.fasterxml.jackson.core.JsonProcessingException;
  11. import com.fasterxml.jackson.databind.ObjectMapper;
  12. import org.slf4j.Logger;
  13. import org.slf4j.LoggerFactory;
  14. import org.springframework.beans.factory.annotation.Autowired;
  15. import org.springframework.data.redis.core.StringRedisTemplate;
  16. import org.springframework.web.bind.annotation.GetMapping;
  17. import org.springframework.web.bind.annotation.RequestMapping;
  18. import org.springframework.web.bind.annotation.RestController;
  19. import java.util.Date;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. /**
  23. * redis发布消息
  24. * @author tn
  25. * @ClassName RedisController
  26. * @description redis接口
  27. * @date 2020-09-30 12:04
  28. */
  29. @RequestMapping("redis")
  30. @RestController
  31. public class RedisMessageController {
  32. private static final Logger log = LoggerFactory.getLogger(RedisMessageController.class);
  33. @Autowired
  34. StringRedisTemplate template;
  35. /**
  36. * 给频道 tn 发送消息
  37. * @return
  38. */
  39. @GetMapping(value = "/syncmessage")
  40. public String SyncMessage(){
  41. for(int i = 1; i <= 5; i++){
  42. try{
  43. // 为了模拟消息,sleep一下。
  44. Thread.sleep(2000);
  45. }catch(InterruptedException ex){}
  46. template.convertAndSend("tn", String.format("tn - 我是消息{%d}号: %tT", i, new Date()));
  47. }
  48. return "success";
  49. }
  50. /**
  51. * 给频道 test 发送消息
  52. * @return
  53. * @throws JsonProcessingException
  54. */
  55. @GetMapping("setMessage")
  56. public String setMessage() throws JsonProcessingException {
  57. Map map = new HashMap();
  58. map.put("name","你好");
  59. map.put("sex","2");
  60. map.put("time",new Date());
  61. template.convertAndSend("test", new ObjectMapper().writeValueAsString(map));
  62. return "success";
  63. }
  64. }
  • 观测项目控制台的输出跟redis管里端的输出

    1. 2020-12-23 13:13:54.222 INFO 16316 --- [ container-7] c.d.r.pub.server.impl.RedisReceiverImpl :
    2. ----------------------------------------------------------
    3. redis监听频道 test 的消息
    4. 消息体:{"sex":"2","name":"你好","time":1608700434197}
    5. ----------------------------------------------------------
    6. 本机:0>SUBSCRIBE test
    7. Switch to Pub/Sub mode. Close console tab to stop listen for messages.
    8. 1) "subscribe"
    9. 2) "test"
    10. 3) "1"
    11. 1) "message"
    12. 2) "test"
    13. 3) "{"sex":"2","name":"你好","time":1608700434197}"
  • 默认项目中接受消息默认为控制台答应如果想要修改 ```java package com.example.redis.pub.message;

import cn.jdevelops.redis.pub.server.RedisReceiverServer; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.connection.Message; import org.springframework.stereotype.Service;

/**

  • @ClassName : MessageSave
  • @Description : redis订阅消息保存起来
  • @Author : tn
  • @Date: 2020-09-11 10:54 */ @Service @Slf4j public class RedisReceiverImpl implements RedisReceiverServer { @Override public String pubMessage(Message message) {

    1. log.info("自定义保存方法:"+message.toString());
    2. log.info("\n----------------------------------------------------------\n\t" +
    3. "redis监听频道 "+new String(message.getChannel())+" 的消息\n\t" +
    4. "消息体:"+new String(message.getBody()) + "\n" +
    5. "----------------------------------------------------------");
    6. return message.toString();

    } } ```