一.創(chuàng)建spring boot項目
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-data-redis/artifactId>
/dependency>
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-web/artifactId>
/dependency>
dependency>
groupId>com.alibaba/groupId>
artifactId>fastjson/artifactId>
version>1.2.41/version>
/dependency>
二.編輯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 RedisTemplateString, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplateString, Object> redisTemplate = new RedisTemplate>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 設(shè)置數(shù)據(jù)存入 redis 的序列化方式,并開啟事務(wù)
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(@Qualifier("RedisTemplateS") RedisTemplateString, Object> redisTemplate, RedisConnectionFactory factory) {
// 如果不配置Serializer,那么存儲的時候缺省使用String,如果用User類型存儲,那么會提示錯誤User can't cast to
// String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
FastJsonRedisSerializerObject> fastJsonRedisSerializer = new FastJsonRedisSerializerObject>(Object.class);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
//redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 開啟事務(wù)
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
/**
* 注入封裝RedisTemplate @Title: redisUtil @return RedisUtil @date
*
*/
@Bean(name = "redisUtils")
public RedisUtils redisUtil(@Qualifier("RedisTemplateS") RedisTemplateString, Object> redisTemplate) {
RedisUtils redisUtil = new RedisUtils();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
四.編寫RedisUtil消息發(fā)布方法
public class RedisUtils {
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
private RedisTemplateString, Object> redisTemplate;
public void setRedisTemplate(RedisTemplateString, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void publish(String channal ,Object obj) {
redisTemplate.convertAndSend(channal,obj );
}
}
五.配置消息監(jiān)聽
@Configuration
public class RedisMessageListener {
/**
* 創(chuàng)建連接工廠
* @param connectionFactory
* @param listenerAdapter
* @return
*/
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter,MessageListenerAdapter listenerAdapter2){
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
//接受消息的key
container.addMessageListener(listenerAdapter,new PatternTopic("phone"));
return container;
}
/**
* 綁定消息監(jiān)聽者和接收監(jiān)聽的方法
* @param receiver
* @return
*/
@Bean
public MessageListenerAdapter listenerAdapter(ReceiverRedisMessage receiver){
return new MessageListenerAdapter(receiver,"receiveMessage");
}
/**
* 注冊訂閱者
* @param latch
* @return
*/
@Bean
ReceiverRedisMessage receiver(CountDownLatch latch) {
return new ReceiverRedisMessage(latch);
}
/**
* 計數(shù)器,用來控制線程
* @return
*/
@Bean
public CountDownLatch latch(){
return new CountDownLatch(1);//指定了計數(shù)的次數(shù) 1
}
}
六.消息訂閱方法
public class ReceiverRedisMessage {
private static final Logger log = LoggerFactory.getLogger(ReceiverRedisMessage.class);
private CountDownLatch latch;
@Autowired
public ReceiverRedisMessage(CountDownLatch latch) {
this.latch = latch;
}
/**
* 隊列消息接收方法
*
* @param jsonMsg
*/
public void receiveMessage(String jsonMsg) {
log.info("[開始消費REDIS消息隊列phone數(shù)據(jù)...]");
try {
log.info("監(jiān)聽者收到消息:{}", jsonMsg);
JSONObject exJson = JSONObject.parseObject(jsonMsg);
User user = JSON.toJavaObject(exJson, User.class);
System.out.println("轉(zhuǎn)化為對象 :"+user);
log.info("[消費REDIS消息隊列phone數(shù)據(jù)成功.]");
} catch (Exception e) {
log.error("[消費REDIS消息隊列phone數(shù)據(jù)失敗,失敗信息:{}]", e.getMessage());
}
latch.countDown();
}
}
七.定時消息發(fā)布測試
@EnableScheduling
@Component
public class PublisherController {
private static final Logger log = LoggerFactory.getLogger(PublisherController.class);
@Autowired
private RedisUtils redisUtils;
@Scheduled(fixedRate = 5000)
public String pubMsg() {
User user=new User(1, "尚***", 26,"男","陜西省xxxx市xxxxxx縣");
redisUtils.publish("phone", user);
log.info("Publisher sendes Topic... ");
return "success";
}
}
八.測試結(jié)果
九.發(fā)布對象User實體
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
private String sex;
private String address;
.....................
}
到此這篇關(guān)于Spring boot+redis實現(xiàn)消息發(fā)布與訂閱的文章就介紹到這了,更多相關(guān)Spring boot redis消息發(fā)布與訂閱內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Spring Cloud Stream分區(qū)分組原理圖解
- Spring Cloud Stream如何實現(xiàn)服務(wù)之間的通訊
- Spring Cloud Stream異常處理過程解析
- 詳解Spring Cloud Stream使用延遲消息實現(xiàn)定時任務(wù)(RabbitMQ)
- SpringBoot+WebSocket+Netty實現(xiàn)消息推送的示例代碼
- SpringBoot集成WebSocket實現(xiàn)前后端消息互傳的方法
- SpringBoot微信消息接口配置詳解
- Spring boot項目redisTemplate實現(xiàn)輕量級消息隊列的方法
- Spring Cloud Stream微服務(wù)消息框架原理及實例解析