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);
            }
        }
    }
  • 相关阅读:
    vue-cli搭建项目结构及引用bootstrap
    万年历案例
    art-template模板渲染及其过滤器
    字符串中全角半角之间的转换
    大话主席(superslide和 touchslide)插件的使用
    JS中对URL进行转码与解码
    animate.css引入实现动画效果
    [MySQL]group by 与 having 结合函数 的统计技巧
    [HTTP] 基本认证的工作流程
    [HTTP]Etag的工作流程
  • 原文地址:https://www.cnblogs.com/DennyZhao/p/9274946.html
Copyright © 2011-2022 走看看