Spring boot+redis實現訊息釋出與訂閱
阿新 • • 發佈:2022-03-27
Spring boot+redis實現訊息釋出與訂閱
https://blog.51cto.com/u_13501268/2489571
一.建立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>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
二.編輯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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
三.配置Redis
@Configuration
public class RedisConfiguration {
/**
* 例項化 RedisTemplate 物件
*
* @return
*/
@Bean("RedisTemplateS")
public RedisTemplate<String, Object> functionDomainRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
return redisTemplate;
}
/**
* 設定資料存入 redis 的序列化方式,並開啟事務
*
* @param redisTemplate
* @param factory
*/
private void initDomainRedisTemplate(@Qualifier("RedisTemplateS") RedisTemplate<String, Object> redisTemplate, RedisConnectionFactory factory) {
// 如果不配置Serializer,那麼儲存的時候預設使用String,如果用User型別儲存,那麼會提示錯誤User can't cast to
// String!
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<Object>(Object.class);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
//redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
//redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
// 開啟事務
redisTemplate.setEnableTransactionSupport(true);
redisTemplate.setConnectionFactory(factory);
}
/**
* 注入封裝RedisTemplate @Title: redisUtil @return RedisUtil @date
*
*/
@Bean(name = "redisUtils")
public RedisUtils redisUtil(@Qualifier("RedisTemplateS") RedisTemplate<String, Object> redisTemplate) {
RedisUtils redisUtil = new RedisUtils();
redisUtil.setRedisTemplate(redisTemplate);
return redisUtil;
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
四.編寫RedisUtil訊息釋出方法
public class RedisUtils {
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void publish(String channal ,Object obj) {
redisTemplate.convertAndSend(channal,obj );
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
五.配置訊息監聽
@Configuration
public class RedisMessageListener {
/**
* 建立連線工廠
* @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;
}
/**
* 繫結訊息監聽者和接收監聽的方法
* @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);
}
/**
* 計數器,用來控制執行緒
* @return
*/
@Bean
public CountDownLatch latch(){
return new CountDownLatch(1);//指定了計數的次數 1
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
六.訊息訂閱方法
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資料...]");
try {
log.info("監聽者收到訊息:{}", jsonMsg);
JSONObject exJson = JSONObject.parseObject(jsonMsg);
User user = JSON.toJavaObject(exJson, User.class);
System.out.println("轉化為物件 :"+user);
log.info("[消費REDIS訊息佇列phone資料成功.]");
} catch (Exception e) {
log.error("[消費REDIS訊息佇列phone資料失敗,失敗資訊:{}]", e.getMessage());
}
latch.countDown();
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
七.定時訊息釋出測試
@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";
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
八.測試結果
九.釋出物件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;
.....................
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.