当前位置:网站首页>Redis cluster simulated message queue

Redis cluster simulated message queue

2022-07-05 19:41:00 Mysterious gate

  1. preparation : install redis And set up clusters
  2. IDEA Create a new project and write a test class RedisTest, Add cluster environment configuration code
  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. Add a test method for joining the team
// Cluster mode test queue operation 
  @Test
  public void testEnterQueue(){
    
    jedisCluster.lpush("queue-1"," Thank you for your support ");
  }
  1. Add team test method
// The cluster mode tests the team operation 
  @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();// Ensure that the main thread ends only after the sub thread ends 
  }

 Insert picture description here
You can see if there is no message in the message queue , Then the thread sleeps 3 Seconds to perform , This can effectively prevent CPU Idle

原网站

版权声明
本文为[Mysterious gate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051911183244.html