当前位置:网站首页>redis集群模拟消息队列

redis集群模拟消息队列

2022-07-05 19:11:00 玄妙之门

  1. 准备工作:安装redis并搭建好集群
  2. IDEA新建项目编写测试类RedisTest,添加集群环境配置代码
  private Jedis jedis;
  private JedisCluster jedisCluster;

  @Before
  public void connectionRedis(){
    
    jedis = new Jedis("192.168.1.118",6379);
    //jedis = new Jedis("192.168.1.20",6382);
    //jedis.auth("123456");

    HostAndPort hp1 = new HostAndPort("192.168.1.20", 6381);
    HostAndPort hp2 = new HostAndPort("192.168.1.20", 6382);
    HostAndPort hp3 = new HostAndPort("192.168.1.20", 6383);
    HostAndPort hp4 = new HostAndPort("192.168.1.20", 6384);
    HostAndPort hp5 = new HostAndPort("192.168.1.20", 6385);
    HostAndPort hp6 = new HostAndPort("192.168.1.20", 6386);
    Set<HostAndPort> hostAndPortSet = new HashSet<>();
    hostAndPortSet.add(hp1);
    hostAndPortSet.add(hp2);
    hostAndPortSet.add(hp3);
    hostAndPortSet.add(hp4);
    hostAndPortSet.add(hp5);
    hostAndPortSet.add(hp6);
    jedisCluster = new JedisCluster(hostAndPortSet);

  }
  1. 添加入队测试方法
//集群模式测试入队操作
  @Test
  public void testEnterQueue(){
    
    jedisCluster.lpush("queue-1","感谢您对本店的支持");
  }
  1. 添加出队测试方法
//集群模式测试出队操作
  @Test
  public void testOutQueue() throws InterruptedException{
    
    Thread t = new Thread("thread-getmsg"){
    
      @Override
      public void run() {
    
        while(true){
    
          String s = jedisCluster.rpop("queue-1");
          if(null==s){
    
            try {
    
              Thread.sleep(3*1000);
            } catch (InterruptedException e) {
    
              e.printStackTrace();
            }
          }
          System.out.println(s);
        }
      }
    };
    t.start();
    t.join();//保证子线程结束后主线程才结束
  }

在这里插入图片描述
可以看到消息队列中如果没有消息,则线程休眠3秒执行,这样可有效防止CPU空转

原网站

版权声明
本文为[玄妙之门]所创,转载请带上原文链接,感谢
https://blog.csdn.net/yangfenggh/article/details/125555922