reids 模仿消息队列

一、消息队列

消息队列简单来说就是一个消费者生产者模型,消费消费资源,生产者生产资源,如何通过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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值