众所周知,redis是nosql数据库,因此大多数情况下,在我们的项目中都是用于数据信息的缓存(例如:商城项目中缓存商品的基本信息),以便于提高数据响应效率,同时又可减少对关系型数据库的压力。
然而redis非关系型数据库的另一个很重要的功能,往往会被大多数人忽略,这个功能就是“消息队列”功能,一般用于电商项目的红包过期通知,或一些项目的日志过滤处理等。
Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 客户端可以订阅任意数量的频道。
下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:
当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端
话不多说:代码如下:
pom.xml中的maven依赖
此处依赖大致提供了springboot项目启动时所需要的依赖以及redis依赖包
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version