当前位置:网站首页>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

边栏推荐
- 【入门】取近似值
- [untitled]
- 毕业论文中word的使用1-代码域标公式
- Agrometeorological environment monitoring system
- EDA open source simulation tool verilator beginner 6: debugging examples
- Leetcode T34: 在排序数组中查找元素的第一个和最后一个位置
- OJ input and output exercise
- Five combination boxing, solving six difficult problems on campus and escorting the construction of educational informatization
- OJ输入输出练习
- [no title] free test questions for constructor municipal direction general foundation (constructor) and theoretical test for constructor municipal direction general foundation (constructor) in 2022
猜你喜欢

7-26 word length (input and output in the loop)

Manually dig XSS vulnerabilities

一套十万级TPS的IM综合消息系统的架构实践与思考

Five combination boxing, solving six difficult problems on campus and escorting the construction of educational informatization

Adding color blocks to Seaborn clustermap matrix
![[getting started] extract non repeating integers](/img/88/3e96df88e980bd98ac112b18a8678c.png)
[getting started] extract non repeating integers
![[getting started] enter the integer array and sorting ID, and sort its elements in ascending or descending order](/img/87/07783593dbabcf29700fa207ecda08.png)
[getting started] enter the integer array and sorting ID, and sort its elements in ascending or descending order

Learn the knowledge you need to know about the communication protocol I2C bus

【入门】提取不重复的整数

軟鍵盤高度報錯
随机推荐
Hijacking a user's browser with beef
Internet of things technology is widely used to promote intelligent water automation management
Comprehensive experiment Li
Contenttype comparison of all types
01 NumPy介绍
Leetcode t39: combined sum
Luogu p3799 demon dream stick
Review of week 280 of leetcode
getInputStream() has already been called for this request
栈实现计算器
XX attack - reflective XSS attack hijacking user browser
使用beef劫持用户浏览器
[redis] it takes you through redis installation and connection at one go
Rumtime 1200 upgrade: London upgrade support, pledge function update and more
[detailed explanation of Huawei machine test] judgment string subsequence [2022 Q1 Q2 | 200 points]
Intelligent constant pressure irrigation system
【入门】截取字符串
golang中的正则表达式使用注意事项与技巧
Agrometeorological environment monitoring system
Maneuvering target tracking -- current statistical model (CS model) extended Kalman filter / unscented Kalman filter matlab implementation