本篇文章小编给大家分享一下Spring boot+redis实现消息发布与订阅的代码实例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
一.创建spring boot项目
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-web
com.alibaba
fastjson
1.2.41
二.编辑yml配置文件
server:
port: 7888
# 日志配置
logging:
config: classpath:log/logback.xml
level:
cn.com.dhcc: info
org.springframework: info
org.springframework.web: info
com.alibaba.nacos.client.naming: error
spring:
redis:
host: localhost
port: 6379
password: *********
database: 1
jedis:
pool:
max-idle: 8
max-active: 8
max-wait: -1
min-idle: 0
timeout: 5000
三.配置Redis
@Configuration
public class RedisConfiguration {
/**
* 实例化 RedisTemplate 对象
*
* @return
*/
@Bean("RedisTemplateS")
public RedisTemplate functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 设置数据存入 redis 的序列化方式,并开启事务
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(@Qualifier("RedisTemplateS") RedisTemplate redisTemplate, RedisConnectionFactory factory) {
// 如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to
// String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
FastJsonRedisSerializer