zoukankan      html  css  js  c++  java
  • Redis简单生产者消费者

    注意: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);
            }
        }
    }
  • 相关阅读:
    HDU2066一个人的旅行(dijkstra)
    HDU2544最短路(dijkstra)
    iOS 入门 界面UI 界面跳转
    Lua 函数作为参数传递时的注意事项
    成为Lua高手之metatable
    Android 之 声音捕捉
    Lua 多变长参数传递之三点(...)
    iOS之声音捕捉
    iOS ZXing 二维码模块的加入
    Windows 7 系统的系统界面语言切换成风骚的英文
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/9274946.html
Copyright © 2011-2022 走看看