SpringBoot Redis 釋出訂閱
1.pom 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.配置
redis:
host: 10.5.6.13
port: 6379
password: sensetime
timeout: 10000
maxIdle: 300
maxTotal: 1000
maxWaitMillis: 1000
minEvictableIdleTimeMillis: 300000
numTestsPerEvictionRun: 1024
timeBetweenEvictionRunsMillis: 30000
testOnBorrow: true
testWhileIdle: true
3.redisConfig
/**
* 建立任務池,執行執行緒等待處理redis的訊息
*/
@Bean
public ThreadPoolTaskScheduler initTaskScheduler() {
if (null != taskScheduler) {
return taskScheduler;
}
taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(20);
return taskScheduler;
}// 定義監聽渠道,名稱為topic1
@Bean
public ChannelTopic topic() {
return new ChannelTopic(topic);
}
/**
* 定義redis的監聽器
*
* @return 監聽容器
*/
@Bean
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
// Redis連線工廠
container.setConnectionFactory(redisConnectionFactory);
// 設定執行任務的執行緒池
container.setTaskExecutor(initTaskScheduler());
// 使用監聽器監聽Redis的訊息
container.addMessageListener(new ConsumerRedisListener(), topic());
return container;}
4.消費監聽器
public class ConsumerRedisListener implements MessageListener {
@Override
public void onMessage(Message message, byte[] pattern) {
// 訊息體
String body = new String(message.getBody());
// 渠道名稱
String topic = new String(pattern);
System.out.println("訊息體:" + body);
System.out.println("渠道名稱:" + topic);
}}
5.釋出-測試
stringRedisTemplate.convertAndSend("faceSearchTopic","hello redis");
6.結果
7.到這步說明已經發布訂閱成功。