当前位置:网站首页>Redis publish subscription
Redis publish subscription
2022-07-01 08:27:00 【PS cool tutorial】
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.12.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
spring:
redis:
database: 0
host: localhost
port: 6379
timeout: 6000 # The connection is too long ( millisecond )
jedis:
pool:
max-active: 1000 # Maximum number of connections in connection pool ( Use a negative value to indicate that there is no limit )
max-wait: -1ms # Connection pool maximum blocking wait time ( Use a negative value to indicate that there is no limit )
max-idle: 10 # Maximum free connections in connection pool
min-idle: 5 # Minimum free connection in connection pool
To configure
RedisConfig
@Configuration
public class RedisConfig {
@Autowired
private RedisConnectionFactory factory;
@Bean
public RedisTemplate<String, Object> redisTemplate() {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(this.factory);
return redisTemplate;
}
}
RedisMessageListener
@Configuration
public class RedisMessageListener {
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// monitor idea passageway
container.addMessageListener(listenerAdapter, new PatternTopic("idea"));
return container;
}
@Bean
public MessageListenerAdapter listenerAdapter(ReceiverRedisMessage receiver) {
MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(receiver,"receiveMessage");
return listenerAdapter;
}
}
ReceiverRedisMessage
@Component
public class ReceiverRedisMessage {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/** * see :MessageListenerAdapter$MostSpecificMethodFilter#matches * jsonMsg: Messages received * topic: Received the message channel * * @param jsonMsg * @param topic */
public void receiveMessage(String jsonMsg,String topic) {
System.out.println(" Listen to the message :->" + jsonMsg);
try {
//ObjectMapper mapper = new ObjectMapper();
//Map map = mapper.readValue(jsonMsg, Map.class);
// The following can be handled json The problem of multiple slashes in strings
MonitorData dto = JSON.parseObject(JSON.parse(jsonMsg).toString(), MonitorData.class);
} catch (Exception e) {
System.out.println(" Failure :"+ jsonMsg);
}
}
}
JsonUtil
public abstract class JsonUtil {
private static final ObjectMapper objectMapper = new ObjectMapper();
public JsonUtil() {
}
public static final Map<String, Object> json2Map(String json) {
if (json == null) {
return null;
} else {
try {
return (Map)objectMapper.readValue(json, Map.class);
} catch (Exception var2) {
throw new RuntimeException(var2);
}
}
}
public static String map2Json(Map<String, Object> map) {
return obj2Json(map);
}
public static final <T> T json2Obj(String content, Class<T> clazz) {
if (StringUtils.isBlank(content)) {
return null;
} else {
try {
return objectMapper.readValue(content, clazz);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
}
public static String obj2Json(Object obj) {
if (obj == null) {
return null;
} else {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException var2) {
throw new RuntimeException(var2);
}
}
}
public static <T> T fromJson(String jsonString, JavaType javaType) {
try {
return objectMapper.readValue(jsonString, javaType);
} catch (Exception var3) {
throw new RuntimeException(var3);
}
}
static {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
}
}
RedisController
@RestController
public class RedisController {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@RequestMapping("pub")
public String pub() {
MonitorData dto = new MonitorData();
dto.setRegionId(100L);
ArrayList<DataDto> dataDtoList = new ArrayList<>();
// dataDto1
DataDto dataDto1 = new DataDto();
dataDto1.setCreateTime(new Date());
dataDto1.setDeviceCode("001");
dataDto1.setIdentifier("L01");
dataDto1.setPropertyName("co2");
dataDto1.setPropertyValue("500ml");
dataDto1.setNormal(true);
dataDto1.setUnit("ml");
dataDto1.setRegionId(50L);
dataDtoList.add(dataDto1);
// dataDto2
DataDto dataDto2 = new DataDto();
dataDto2.setCreateTime(new Date());
dataDto2.setDeviceCode("002");
dataDto2.setIdentifier("L02");
dataDto2.setPropertyName("co2");
dataDto2.setPropertyValue("500ml");
dataDto2.setNormal(true);
dataDto2.setUnit("ml");
dataDto2.setRegionId(51L);
dataDtoList.add(dataDto2);
// message
String message = JsonUtil.obj2Json(dataDtoList);
dto.setMessage(message);
String pubMsg = JsonUtil.obj2Json(dto);
System.out.println(" Send a message :->"+pubMsg);
redisTemplate.convertAndSend("idea", JsonUtil.obj2Json(pubMsg));
return "ok";
}
}
Client subscription topics

边栏推荐
- 程序员养生宝典
- Stack implementation calculator
- [detailed explanation of Huawei machine test] judgment string subsequence [2022 Q1 Q2 | 200 points]
- 【入门】输入n个整数,输出其中最小的k个
- Codeworks round 803 (Div. 2) VP supplement
- leetcode T31:下一排列
- [getting started] intercepting strings
- On June 30, 2022, the record of provincial competition + national competition of Bluebridge
- Review of week 280 of leetcode
- 2022 ordinary scaffolder (special type of construction work) examination question bank and the latest analysis of ordinary scaffolder (special type of construction work)
猜你喜欢

Koltin35, headline Android interview algorithm

Suivi des cibles de manoeuvre - - mise en oeuvre du modèle statistique actuel (modèle CS) filtre Kalman étendu / filtre Kalman sans trace par MATLAB
![[untitled]](/img/be/3523d0c14d555b293673af2b6fbcff.jpg)
[untitled]

SPL-安装与基本使用(二)

CPU設計實戰-第四章實踐任務一簡單CPU參考設計調試
![Thread safety analysis of [concurrent programming JUC] variables](/img/f9/a3604bec6f7e5317dd2c578da73018.jpg)
Thread safety analysis of [concurrent programming JUC] variables

【入门】输入整型数组和排序标识,对其元素按照升序或降序进行排序

PostgreSQL source code learning (26) -- windows vscode remote debugging PostgreSQL on Linux

谈谈数字化转型的几个关键问题

Keithley 2100 software 𞓜 Keithley2400 test software ns SourceMeter
随机推荐
empirical study and case study
【力扣10天SQL入门】Day9 控制流
一套十万级TPS的IM综合消息系统的架构实践与思考
EDA开源仿真工具verilator入门6:调试实例
【入门】截取字符串
【入门】输入整型数组和排序标识,对其元素按照升序或降序进行排序
String coordinates of number to excel
7-26 word length (input and output in the loop)
php laravel微信支付
Analysis of slice capacity expansion mechanism
Yolov5 advanced 7 target tracking latest environment setup
2022.6.30 省赛+蓝桥国赛记录
[untitled]
Use threejs simple Web3D effect
Keithley 2100 software 𞓜 Keithley2400 test software ns SourceMeter
[detailed explanation of Huawei machine test] judgment string subsequence [2022 Q1 Q2 | 200 points]
软键盘高度报错
Agrometeorological environment monitoring system
2022 examination summary of quality controller civil engineering direction post skills (quality controller) and reexamination examination of quality controller civil engineering direction post skills
使用 setoolkit 伪造站点窃取用户信息