用Redis实现的简易的消息队列,跟之前写的山寨版消息队列差不多效果。
public static void main(String[] args) {
RedissonClient redisson = null;
try{
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6379");
redisson = Redisson.create(config);
RQueue r = redisson.getQueue("someQueue");
//生产消息
for(int i=0;i<10;i++){
r.offer(new Integer(i).toString());
}
//消费消息
Thread t1 = new Thread(()->{
RedissonClient redisson2 = Redisson.create(config);
while (true){
try {
Thread.sleep(1000);
}catch (Exception ex){
}
RLock rLock = redisson2.getLock("qLock");
rLock.lock();
RQueue r2 = redisson2.getQueue("someQueue");
if(r2.size()<=0){
rLock.unlock();
break;
}
System.out.println("Thread1:"+r2.poll().toString());
rLock.unlock();
}
redisson2.shutdown();
});
t1.start();
Thread t2 = new Thread(()->{
RedissonClient redisson2 = Redisson.create(config);
while (true){
try {
Thread.sleep(1000);
}catch (Exception ex){
}
RLock rLock = redisson2.getLock("qLock");
rLock.lock();
RQueue r2 = redisson2.getQueue("someQueue");
if(r2.size()<=0){
rLock.unlock();
break;
}
System.out.println("Thread2:"+r2.poll().toString());
rLock.unlock();
}
redisson2.shutdown();
});
t2.start();
Thread t3 = new Thread(()->{
RedissonClient redisson2 = Redisson.create(config);
while (true){
try {
Thread.sleep(1000);
}catch (Exception ex){
}
RLock rLock = redisson2.getLock("qLock");
rLock.lock();
RQueue r2 = redisson2.getQueue("someQueue");
if(r2.size()<=0){
rLock.unlock();
break;
}
System.out.println("Thread3:"+r2.poll().toString());
rLock.unlock();
}
redisson2.shutdown();
});
t3.start();
}
catch (Exception ex){
System.out.println(ex.getMessage());
}
finally {
redisson.shutdown();
}
}
运行结果:
image.png
网友评论