spring集成redis消息列队

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;

import com.qmtt.api.web.controller.TaskController;

public class RedisQueue implements InitializingBean {
    private static final Logger log = Logger.getLogger(TaskController.class);

    @Value("${redis.queue}")
    public String queueName;
    @Autowired
    RedisTemplate redisTemplate;
    BoundListOperations<String, String> listRedisTemplate;

    public void pushMsg(String value) {
        listRedisTemplate.leftPush(value);
    }

    class ListenerThread extends Thread {
        @Override
        public void run() {
            try {
                while (true) {
                    String value = listRedisTemplate.rightPop();
                    if (StringUtils.isNotEmpty(value)) {

                    }
                    System.out.println(value);
                    Thread.sleep(5000);
                }
            } catch (Exception e) {
                log.error("", e);
            }
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        listRedisTemplate = redisTemplate.boundListOps(queueName);
        // 启动监听
        ListenerThread thread = new ListenerThread();
        thread.setDaemon(true);
        thread.start();
    }
}

 

package com.qmtt.api.message.consumer;
import org.apache.commons.lang.StringUtils;import org.apache.log4j.Logger;import org.springframework.beans.factory.InitializingBean;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.data.redis.core.BoundListOperations;import org.springframework.data.redis.core.RedisTemplate;
import com.qmtt.api.web.controller.TaskController;
public class RedisQueue implements InitializingBean {private static final Logger log = Logger.getLogger(TaskController.class);
@Value("${redis.queue}")public String queueName;@AutowiredRedisTemplate redisTemplate;BoundListOperations<String, String> listRedisTemplate;
public void pushMsg(String value) {listRedisTemplate.leftPush(value);}
class ListenerThread extends Thread {@Overridepublic void run() {try {while (true) {String value = listRedisTemplate.rightPop();if (StringUtils.isNotEmpty(value)) {
}System.out.println(value);Thread.sleep(5000);}} catch (Exception e) {log.error("", e);}}}
@Overridepublic void afterPropertiesSet() throws Exception {listRedisTemplate = redisTemplate.boundListOps(queueName);// 启动监听ListenerThread thread = new ListenerThread();thread.setDaemon(true);thread.start();}}

posted @ 2017-05-22 17:25  wujf  阅读(1971)  评论(0编辑  收藏  举报