介绍
- 当初做消息推送的时候考虑了websocket跟redis两个方案
- 虽然最终选择了websocket,但是redis的demo我也做了
-
引入依赖
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- redis - push --><dependency><groupId>cn.jdevelops</groupId><artifactId>caches-redis-pub</artifactId><version>2.0.3</version></dependency>
开始配置
默认配置了两个频道
- 默认配置本机redis (保证redis正常运行且没有密码)
- 如果要用自己的频道和修改默认连接请在
application.properties添加以下配置 ```yaml jdevelops: redis: cache:
spring: redis: database: 1 host: 127.0.0.1 port: 6379 timeout: 2000pub:pattern-topic: # 频道名- test- tn
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
<a name="YqswM"></a># 示例测试<a name="6e5JG"></a>## 观测- 打开redis管理端(命令行)输入命令 `SUBSCRIBE 频道名`- 默认频道有两个: test, tn- 调用接口```javapackage com.example.redis.pub.controller;import com.fasterxml.jackson.core.JsonProcessingException;import com.fasterxml.jackson.databind.ObjectMapper;import org.slf4j.Logger;import org.slf4j.LoggerFactory;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.RestController;import java.util.Date;import java.util.HashMap;import java.util.Map;/*** redis发布消息* @author tn* @ClassName RedisController* @description redis接口* @date 2020-09-30 12:04*/@RequestMapping("redis")@RestControllerpublic class RedisMessageController {private static final Logger log = LoggerFactory.getLogger(RedisMessageController.class);@AutowiredStringRedisTemplate template;/*** 给频道 tn 发送消息* @return*/@GetMapping(value = "/syncmessage")public String SyncMessage(){for(int i = 1; i <= 5; i++){try{// 为了模拟消息,sleep一下。Thread.sleep(2000);}catch(InterruptedException ex){}template.convertAndSend("tn", String.format("tn - 我是消息{%d}号: %tT", i, new Date()));}return "success";}/*** 给频道 test 发送消息* @return* @throws JsonProcessingException*/@GetMapping("setMessage")public String setMessage() throws JsonProcessingException {Map map = new HashMap();map.put("name","你好");map.put("sex","2");map.put("time",new Date());template.convertAndSend("test", new ObjectMapper().writeValueAsString(map));return "success";}}
观测项目控制台的输出跟redis管里端的输出
2020-12-23 13:13:54.222 INFO 16316 --- [ container-7] c.d.r.pub.server.impl.RedisReceiverImpl :----------------------------------------------------------redis监听频道 test 的消息消息体:{"sex":"2","name":"你好","time":1608700434197}----------------------------------------------------------本机:0>SUBSCRIBE testSwitch to Pub/Sub mode. Close console tab to stop listen for messages.1) "subscribe"2) "test"3) "1"1) "message"2) "test"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) { log.info("自定义保存方法:"+message.toString());log.info("\n----------------------------------------------------------\n\t" +"redis监听频道 "+new String(message.getChannel())+" 的消息\n\t" +"消息体:"+new String(message.getBody()) + "\n" +"----------------------------------------------------------");return message.toString();
} } ```
