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);
            }
        }
    }
  • 相关阅读:
    [Liferay6.2.2]AUI的小坑:input的type属性
    官方Tomcat 8.0.24 Web漏洞整改记录
    通过ajax访问Tomcat服务器web service接口时出现No 'Access-Control-Allow-Origin' header问题的解决办法
    前端开发之BOM和DOM
    前端开发之JavaScript
    前端开发之CSS
    前端开发之HTML
    python编程之进程
    python编程之操作系统基础
    python网络编程之socket
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/9274946.html
Copyright © 2011-2022 走看看