一、消息队列
消息队列简单来说就是一个消费者生产者模型,消费消费资源,生产者生产资源,如何通过redis来实现消息队列,会发觉redis中list结构很适合处理这类问题,list类型可以用来在商城系统中表明某一个流程,将一个个流程以lpush的方式放入到list中,将结束的流程以rpop的方式结束当前路程。
二、Jedis资源池生成实例
注意需要添加资源池的配置,由于自己刚开始只是创建了资源池,资源池属性采用了默认属性,导致生产者生产8个资源数目,通过单例模式返回一个Jedis对象
//内部静态类返回jedis资源
static class JedisPoolUtil {
private static JedisPool pool = null;
static {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxIdle(30);//最大闲置数目
config.setMaxWaitMillis(3000);//最大闲置等待时间
config.setMaxTotal(100);//最大连接数
pool = new JedisPool(config, "127.0.0.1");
}
public static Jedis getJedis() {
return pool.getResource();
}
}
三、生产者
5个线程来模拟生产者,不断向redis:queue中添加资源
class Publish extends Thread {
private volatile int count = 0;
private String key = "redis:queue";
public void putMessage(String message) {
Jedis jedis = JedisPoolUtil.getJedis();
Long size = jedis.lpush(key, message);
System.out.println(Thread.currentThread().getName()+"put ,size:"+size+",count:"+count);
count++;
}
@Override
public synchronized void run() {
//每个线程运行5次
for (int i = 0; i < 5; i++) {
putMessage("message:"+count);
}
}
public static void main(String[] args) {
Publish pub = new Publish();
Thread t1 = new Thread(pub,"thread_1");
Thread t2 = new Thread(pub,"thread_2");
Thread t3 = new Thread(pub,"thread_3");
Thread t4 = new Thread(pub,"thread_4");
Thread t5 = new Thread(pub,"thread_5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
四、消费者
刚开始使用rpop命令来获取list中的资源,后边发现,消费线程可能会发生空转(没有获取到资源),因此选择使用brpop的方式来获取,如果list中不存在资源的话,当前运行线程就会阻塞。
public class Consumer extends Thread {
private final String key = "redis:queue";
private volatile int count = 0;
public void consumer() {
Jedis jedis = JedisPoolUtil.getJedis();
List<String> message = jedis.brpop(0, key);
System.out.println(Thread.currentThread().getName() + "count:" + count + "get:" + message);
count++;
}
@Override
public void run() {
while (true) {
consumer();
}
}
public static void main(String[] args) {
Consumer consumer = new Consumer();
Thread t1 = new Thread(consumer, "Thread_1");
Thread t2 = new Thread(consumer, "Thread_2");
t1.start();
t2.start();
}
}
参考
【1】https://www.cnblogs.com/qlqwjy/p/9763754.html