- 准备工作:安装redis并搭建好集群
- 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);
}
- 添加入队测试方法
//集群模式测试入队操作
@Test
public void testEnterQueue(){
jedisCluster.lpush("queue-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空转