为什么Redis作为消息中间件会被放在第二篇呢?想想,互联网项目中,基本上都离不开Redis,因为它可以作为缓存。很多时候,我们要在项目中引入一种新的组件时,往往需要考虑它的必要性。如果Redis本身的消息队列功能已经能满足大多数时候的需要了,为什么还要再引入MQ?

1. Redis作为消息中间件的可行性

Redis虽然没有像MQ一样支持丰富的消息传播能力,但是在大多数场景中已经足够用了。通常有两种实现方式:(1)Redis支持list数据类型,而且提供了pop和push方法,允许我们像使用Queue一样操作list。具体做法是:客户端在list一端往里塞,服务端在另一端用死循环往出取,峨眉有数据就一直阻塞。这种方式不够友好,而且会有性能问题。感兴趣的可以翻翻我以前的博客。(2)发布订阅模式。这种模式就和其他的消息队列很像了。

2. 结合easy-asyn使用Redis的发布订阅模式

2.1 maven引入(最新版本

<dependency>
	<groupId>io.github.xiaoyudeguang</groupId>
	<artifactId>easy-redis</artifactId>
	<version>最新版本</version>
</dependency>

 为什么要把easy-redis作为一个单独的工具发布出来呢?从它的名称你也能猜出来,作为消息队列只是它的一部分,后续会考虑把缓存也集成进来。

2.2 下载Redis的压缩包后再cmd里执行redis-server.exe redis.windows.conf命令启动起来,因为是本地所以在SpringBoot项目里不配置也是可以直接访问的。

2.3 把上一篇博客的消息发布代码复制过来,稍微修改一下(消费者代码不用管):

package com.zlyx.test.asyn;

import org.springframework.context.ApplicationContext;

import com.zlyx.easy.asyn.utils.MsgUtils;
import com.zlyx.easy.core.annotations.SpringBean;
import com.zlyx.easy.core.event.IHandlerOnRefreshed;
import com.zlyx.easy.core.model.UserModel;
import com.zlyx.easy.core.utils.LogUtils;
import com.zlyx.easy.redis.utils.RedisUtils;

@SpringBean(todo = { "Redis异步消息发布" })
public class AsynMsgSender implements IHandlerOnRefreshed {

	@Override
	public void doOnRefreshed(ApplicationContext context) throws Exception {
		MsgUtils.doTopic("easy-asyn", "MQ异步消息测试@topic");
		//MsgUtils.doQuque("easy-asyn", "MQ异步消息测试@queue"); //Redis模式不支持queue
	}
}

2.4 效果:

2019-09-07 21:48:22.736  INFO 2144 --- [enerContainer-2] com.zlyx.test.asyn.AsynMsgListener       : {"name":"Redis异步消息推送","age":12}