Redis消息订阅
第一步 监听配置,设置订阅topic
package com.xuexi.common.redis;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
/**
* @Date: 2020/5/15
*/
@Configuration
public class RedisSubListenerConfig {
@Bean
MessageListenerAdapter listenerAdapter1 () {
MessageListenerAdapter receiveMessage = new MessageListenerAdapter(new RedisSubHandler(), "message1");
return receiveMessage;
}
@Bean
MessageListenerAdapter listenerAdapter2 () {
MessageListenerAdapter receiveMessage = new MessageListenerAdapter(new RedisSubHandler(), "message2");
return receiveMessage;
}
@Bean
RedisMessageListenerContainer container (@Qualifier("connectionFactory")RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter1,MessageListenerAdapter listenerAdapter2 ) {
RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
redisMessageListenerContainer.setConnectionFactory(connectionFactory);
redisMessageListenerContainer.addMessageListener(listenerAdapter1,new PatternTopic("topic1"));
redisMessageListenerContainer.addMessageListener(listenerAdapter2,new PatternTopic("topic2"));
return redisMessageListenerContainer;
}
}
第二步 接收订阅处理
package com.xuexi.common.redis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @Date:
*/
@Slf4j
@Component
public class RedisSubHandler {
public void message1(String message) throws InterruptedException {
//业务处理
log.info("收到topic1订阅消息");
}
public void message2(String message) throws InterruptedException {
//业务处理
log.info("收到topic2订阅消息");
}
}