redis消息队列启动

// 消息监听
addMqListener();
在程序启动的时候,自动启动消息监听。
private void addMqListener() {
MessageQueueUtil.subscribe(null, new MessageQueueListener());//調用工具類的subscribe方法}
}

public class MessageQueueUtil {
/**
     * 订阅
     * @param interestingTopic 主题
     * @param listenner 监听器
     */
    public static void subscribe(String[] interestingTopic, Object listenner) {
    new Thread(new SubscribeThread(interestingTopic, listenner)).start();
    }
}

/**
 * 发布/订阅模式的订阅观察工作线程
 */
public class SubscribeThread implements Runnable{
private String[] interestingTopic;

private Object listenner;

public SubscribeThread(String[] interestingTopic, Object listenner){
this.interestingTopic = interestingTopic;
this.listenner = listenner;
}

@Override
public void run() {
SubscriberProxyService subscreberProxy = (SubscriberProxyService)ApplicationUtil.getBean("subscriberProxyService");
subscreberProxy.subscribe(interestingTopic, listenner);
}
}




@Override
public void subscribe(String[] topics, Object callback) {
if (redisContainer == null) {
redisContainer = (RedisMessageListenerContainer) ApplicationUtil
.getBean("redisContainer");
}


if (redisContainer == null) {
logger.info("未获取到redisContainer实例");
return;
}

//获取公共订阅的主题
List<ChannelTopic> topicList = new ArrayList<ChannelTopic>();
if(topics != null) {
for (String topicName : topics) {
ChannelTopic topic = new ChannelTopic(business+topicName);
topicList.add(topic);
}
}

//获取方法私有订阅的主题
Map<String,List<ChannelTopic>> methodTopicMap = parseMethodTopic(callback.getClass());
Iterator<Entry<String,List<ChannelTopic>>> it = methodTopicMap.entrySet().iterator();
while(it.hasNext()){
Entry<String,List<ChannelTopic>> entry = it.next();
List<ChannelTopic> newTopicList = new ArrayList<ChannelTopic>();
MessageListener listener = new RedisListener(callback, entry.getKey());
newTopicList.addAll(topicList);
newTopicList.addAll(entry.getValue());
redisContainer.addMessageListener(listener, newTopicList);
}
}

/**
* 解析注解iotasSubscribe的方法,返回方法和主题间的映射关系。
* @param clazz
* @return
*/
private Map<String,List<ChannelTopic>> parseMethodTopic(Class<?> clazz) {
Map<String, List<ChannelTopic>> methodTopicMap = new HashMap<String,List<ChannelTopic>>();


for (Method method : clazz.getDeclaredMethods()) {
IotasSubscribe subAnnotation = method.getAnnotation(IotasSubscribe.class);
List<ChannelTopic> topicList = new ArrayList<ChannelTopic>();


if (subAnnotation != null) {
String[] topicsStr = subAnnotation.topic().split(",");
for(String topicName : topicsStr){
ChannelTopic topic = new ChannelTopic(topicName);
topicList.add(topic);
}
}
if(!topicList.isEmpty()) {
methodTopicMap.put(method.getName(),topicList);
}
}
return methodTopicMap;
}
这样就实现了消息队列的自启动。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值