当前位置:网站首页>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
边栏推荐
- EDA open source simulation tool verilator beginner 6: debugging examples
- 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
- To prevent "activation" photos from being muddled through, databao "live detection + face recognition" makes face brushing safer
- Yolov5 advanced six target tracking environment construction
- 【力扣10天SQL入门】Day10 控制流
- 华为机试真题专栏订阅指引
- Book of quantitative trading - reading notes of the man who conquers the market
- Erreur de hauteur du clavier souple
- [untitled]
- 手工挖XSS漏洞
猜你喜欢
[introduction] approximate value
软键盘高度报错
【刷题】字符统计【0】
7-26 word length (input and output in the loop)
The Windows C disk is full
web254
使用 setoolkit 伪造站点窃取用户信息
Practice and Thinking on the architecture of a set of 100000 TPS im integrated message system
shardingSphere
Maneuvering target tracking -- current statistical model (CS model) extended Kalman filter / unscented Kalman filter matlab implementation
随机推荐
Leetcode T29: 两数相除
Serial port oscilloscope software ns-scope
Access report realizes subtotal function
PHP laravel wechat payment
Leetcode T39: 组合总和
Airsim radar camera fusion to generate color point cloud
栈实现计算器
CPU设计实战-第四章实践任务一简单CPU参考设计调试
empirical study and case study
Book of quantitative trading - reading notes of the man who conquers the market
使用beef劫持用户浏览器
Manually dig XSS vulnerabilities
Agrometeorological environment monitoring system
P4 installation bmv2 detailed tutorial
手工挖XSS漏洞
网关gateway-88
[no title] free test questions for constructor municipal direction general foundation (constructor) and theoretical test for constructor municipal direction general foundation (constructor) in 2022
Intelligent water and fertilizer integrated control system
Yolov5进阶之六目标追踪环境搭建
01 NumPy介绍