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);
            }
        }
    }
  • 相关阅读:
    2003开机自动登陆然后马上锁定计算机
    修改DNS、网关的VBS代码,不需重起即时生效
    页面自动刷新代码
    dos命令给权限
    无法运行VBS代码
    去掉2003或2kserver版的系统启动报错
    让易语言的信息框总在最前
    教你轻松搞定RJ45网线接头
    小技巧:如何设定永久通用WinRAR压缩密码
    Bootstrap入门教程
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/9274946.html
Copyright © 2011-2022 走看看