注意:redis客户端执行是单线程的,不能将客户端放在外面,内部执行使用多线程的方式。

        // 创建生产端连接
        final Jedis jedisProducter = new Jedis(R_HOST, R_PORT);
        jedisProducter.auth(R_AUTO);
        
        Runnable th1= new Runnable() {
            @Override
            public void run() {
                jedisProducter.lpush(COMMON_KEY_APPLE, "producter2: ");
            }
        };

以上写法就会出错。除非写在一起。

生产者:

/**
 * Redis实现消息队列
 * @author DennyZhao
 * @date 2018/07/06
 */
public class RedisQueueProducter {
    
    private final static String R_HOST="127.0.0.1";
    private final static String R_AUTO = "dennyzhao";
    private final static int R_PORT = 6380;
    private final static String COMMON_KEY_APPLE = "APPLE";

    public static void main(String[] args) throws InterruptedException {
        // 创建生产端连接
        final Jedis jedisProducter = new Jedis(R_HOST, R_PORT);
        jedisProducter.auth(R_AUTO);        
        
        
        while(true) {
            //消费
            long lenth = jedisProducter.llen(COMMON_KEY_APPLE);
            // 生产
            if(lenth < 10) {
                System.out.println("库存告急.....");
                Random sc = new Random();   
                jedisProducter.lpush(COMMON_KEY_APPLE, "producter2: " + sc.nextInt(8));
            }
            Thread.sleep(1000);
        }
    }
}

消费者:

/**
 * Redis实现消息队列
 * @author DennyZhao
 * @date 2018/07/06
 */
public class RedisQueueCustomer {
    
    private final static String R_HOST="127.0.0.1";
    private final static String R_AUTO = "dennyzhao";
    private final static int R_PORT = 6380;
    private final static String COMMON_KEY_APPLE = "APPLE";

    public static void main(String[] args) throws InterruptedException {

        
        // 创建消费者连接
        Jedis jedisCustomer = new Jedis(R_HOST, R_PORT);
        jedisCustomer.auth(R_AUTO);
        
        
        
        while(true) {
            //消费
            System.out.println(jedisCustomer.blpop(2, COMMON_KEY_APPLE));
    
            Thread.sleep(1000);
        }
    }
}

 

posted on 2018-07-06 17:55  zhaoqiang1980  阅读(219)  评论(0编辑  收藏  举报