Redis實(shí)現(xiàn)消息的發(fā)布和訂閱
1、在springboot項(xiàng)目的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.4.5</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>spring-boot-redis-message</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-redis-message</name>
<description>spring-boot-redis-message</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2、在application.properties中配置redis參數(shù)
# Redis數(shù)據(jù)庫(kù)索引(默認(rèn)為0)
spring.redis.database=0
# Redis服務(wù)器地址
spring.redis.host=127.0.0.1
# Redis服務(wù)器連接端口
spring.redis.port=6379
# Redis服務(wù)器連接密碼(默認(rèn)為空)
spring.redis.password=
# 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制)
spring.redis.jedis.pool.max-active=10
# 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 連接池中的最大空閑連接
spring.redis.jedis.pool.max-idle=10
# 連接池中的最小空閑連接
spring.redis.jedis.pool.min-idle=0
# 連接超時(shí)時(shí)間(毫秒)
spring.redis.timeout=1000ms
3、redis的配置類(lèi)
package com.example.springbootredismessage.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.net.UnknownHostException;
/**
* @author zhangshixing
* @date 2021年11月06日 9:44
* redis 配置類(lèi)
*/
@Configuration
public class RedisConfig {
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
StringRedisSerializer stringSerial = new StringRedisSerializer();
// redis key 序列化方式使用stringSerial
template.setKeySerializer(stringSerial);
// redis value 序列化方式使用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// redis hash key 序列化方式使用stringSerial
template.setHashKeySerializer(stringSerial);
// redis hash value 序列化方式使用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4、redis消息發(fā)布和監(jiān)聽(tīng)
4.1 發(fā)送消息
package com.example.springbootredismessage.controller;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
/**
* @author zhangshixing
* @date 2021年11月07日 11:18
*/
@RestController
@RequestMapping(value = "rest/redis")
public class RedisSendMessageController {
@Resource
private RedisTemplate redisTemplate;
@RequestMapping(value = "send/message", method = RequestMethod.GET)
public void testPush(@RequestParam("body") String body) {
/**
* 使用redisTemplate的convertAndSend()函數(shù),
* String channel, Object message
* channel代表管道,
* message代表發(fā)送的信息
*/
redisTemplate.convertAndSend("test_topic", body);
System.out.println("發(fā)送消息成功,channel:test_topic , messgae:" + body);
}
}
4.2 接收消息
package com.example.springbootredismessage.config;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.stereotype.Component;
import java.io.UnsupportedEncodingException;
/**
* @author zhangshixing
* @date 2021年11月07日 11:22
* redis訂閱方:接收消息
* 為了接收 Redis 渠道發(fā)送過(guò)來(lái)的消息,我們先定義一個(gè)消息監(jiān)聽(tīng)器( MessageListener )
*/
@Component
public class MyRedisSubscribeListener implements MessageListener {
/**
* 這里的 onMessage 方法是得到消息后的處理方法, 其中 message 參數(shù)代表 Redis 發(fā)送過(guò)來(lái)的消息,
* pattern是渠道名稱(chēng),onMessage方法里打印了它們的內(nèi)容。這里因?yàn)闃?biāo)注了@Component注解,所以
* 在Spring Boot掃描后,會(huì)把它自動(dòng)裝配到IoC容器中 ,監(jiān)聽(tīng)著對(duì)象RedisMessageListener會(huì)自動(dòng)
* 將消息進(jìn)行轉(zhuǎn)換。
*
* @param message
* @param bytes
*/
@Override
public void onMessage(Message message, byte[] bytes) {
System.out.println("接收消息!");
//消息體
String body = null;
try {
//解決string亂碼
body = new String(message.getBody(), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//渠道名稱(chēng)
String topic = new String(bytes);
System.out.println("消息體:" + body);
System.out.println("渠道名稱(chēng):" + topic);
}
}
5、啟動(dòng)類(lèi)
package com.example.springbootredismessage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootRedisMessageApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootRedisMessageApplication.class, args);
}
}
6、測(cè)試
http://localhost:8080/rest/redis/send/message?body=helloworld
文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-649185.html
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-649185.html
到了這里,關(guān)于Redis實(shí)現(xiàn)消息的發(fā)布和訂閱的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!