redis不僅是一個(gè)非常強(qiáng)大的非關(guān)系型數(shù)據(jù)庫(kù)申尼,它同時(shí)還擁有消息中間件的pub/sub功能垮卓,在spring boot中進(jìn)行如下設(shè)置就可以使用redis的pub/sub功能
1、新建一個(gè)消息發(fā)布者师幕,設(shè)置主題為topic
/**
* @author Gjing
*
* 消息發(fā)送者
**/
@RestController
public class PubController {
@Resource
private StringRedisTemplate stringRedisTemplate;
private static AtomicInteger count = new AtomicInteger();
@PostMapping("/message")
public void sendMessage() {
int i = count.incrementAndGet();
stringRedisTemplate.convertAndSend("topic", "消息" + i);
}
}
2粟按、定義消息監(jiān)聽(tīng)者
/**
* @author Gjing
*
* 消息監(jiān)聽(tīng)者
**/
@Slf4j
public class Receiver {
public void receiveMessage(String message) {
log.info("監(jiān)聽(tīng)者1收到消息:{}", message);
}
}
3、定義配置類(lèi)霹粥,配置redis監(jiān)聽(tīng)者容器和監(jiān)聽(tīng)者適配器
/**
* @author Gjing
**/
@Configuration
public class RedisConfiguration {
/**
* 消息適配器
*
* 綁定消息監(jiān)聽(tīng)者和接收監(jiān)聽(tīng)的方法,必須要注入這個(gè)監(jiān)聽(tīng)器灭将,不然會(huì)報(bào)錯(cuò)
* @return MessageListenerAdapter
*/
@Bean
public MessageListenerAdapter listenerAdapter() {
return new MessageListenerAdapter(new Receiver(), "receiveMessage");
}
/**
* 定義消息監(jiān)聽(tīng)者容器
* @param connectionFactory 連接工廠
* @param listenerAdapter 消息處理器
* @return RedisMessageListenerContainer
*/
@Bean
public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
listenerContainer.addMessageListener(listenerAdapter, new PatternTopic("topic"));
return listenerContainer;
}
}
運(yùn)行結(jié)果
以上為個(gè)人觀點(diǎn),如有誤歡迎各位指正