SpringBoot+Redis實現消息的發佈與訂閲

語言: CN / TW / HK

SpringBoot+Redis實現消息的發佈與訂閲

1.什麼是redis的發佈與訂閲

在官網的文檔介紹中有一行介紹:Redis是一個快速穩定的發佈/訂閲消息系統。

2.Redis發佈訂閲

機制

Redis提供了發佈與訂閲的功能,可以用於消息的傳輸,Redis的發佈訂閲機制包括三部分,發佈者、訂閲者和Channel(主題或者隊列)。

Redis消息的發佈與訂閲機制.png

3.命令行實現功能

訂閲主題

Redis採用SUBSCRIBE channel命令訂閲某個主題,返回的參數subscribe表示已經成功訂閲主題,第二個參數表示訂閲的主題名稱,第三個表示當前訂閲數

shell 127.0.0.1:6379> SUBSCRIBE ORDER-PAY-SUCCESS Reading messages... (press Ctrl-C to quit) 1) "subscribe" 2) "ORDER-PAY-SUCCESS" 3) (integer) 1

模式匹配訂閲

模式匹配功能是允許客户端訂閲匹配某種模式的頻道,Redis採用PSUBSCRIBE channel命令訂閲匹配某種模式的所有頻道,用*表示模式,*可以被任意值代替。

shell 127.0.0.1:6379> PSUBSCRIBE ORDER-PAY-* Reading messages... (press Ctrl-C to quit) 1) "psubscribe" 2) "ORDER-PAY-*" 3) (integer) 1

發佈消息

Redis採用PUBLISH channel message命令在某個主題上發佈消息,返回的參數是接收到消息的訂閲者個數

shell 127.0.0.1:6379> PUBLISH ORDER-PAY-SUCCESS DD202109071525 (integer) 1

取消訂閲

Redis採用UNSUBSCRIBE channelPUNSUBSCRIBE channel命令取消某個主題的訂閲,由於Redis的訂閲操作是阻塞式的,因此一旦客户端訂閲了某個頻道或模式,就將會一直處於訂閲狀態直到退出。在 SUBSCRIBEPSUBSCRIBEUNSUBSCRIBEPUNSUBSCRIBE 命令中,其返回值都包含了該客户端當前訂閲的頻道和模式的數量,當這個數量變為0時,該客户端會自動退出訂閲狀態。

shell 127.0.0.1:6379> UNSUBSCRIBE ORDER-PAY-SUCCESS 1) "unsubscribe" 2) "ORDER-PAY-SUCCESS" 3) (integer) 0 127.0.0.1:6379> PUNSUBSCRIBE ORDER-PAY-SUCCESS 1) "punsubscribe" 2) "ORDER-PAY-SUCCESS" 3) (integer) 0

測試

首先三個訂閲者訂閲ORDER-PAY-SUCCESS主題,當發送者在這個主題內發送訂單號時,所有的訂閲者都會收到這個主題的消息。

Snipaste_2021-09-07_15-38-49.png

4.SpringBoot實現功能

Springboot整合Redis

引入依賴包

xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>2.2.10.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> <version>2.4.1</version> </dependency> </dependencies>

配置yaml文件

```yaml server: port: 8888

spring: application: name: spring-boot-redis redis: host: 127.0.0.1 port: 6379 ```

配置消息監聽

```java import com.demo.redis.listener.MessageListener; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.listener.PatternTopic; import org.springframework.data.redis.listener.RedisMessageListenerContainer; import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

/* * @author Bai * @date 2021/4/29 上午 11:17 * @description / @Configuration public class RedisMessageConfig {

/**
 * 監聽訂單支付完成主題
 */
private static final String ORDER_PAY_SUCCESS = "ORDER-PAY-SUCCESS";

/**
 * 注入消息監聽適配器
 * @param messageListener
 * @return {@link MessageListenerAdapter}
 * @throws
 * @author Bai
 * @date 2021/9/7 下午 03:54
 */
@Bean
public MessageListenerAdapter getMessageListenerAdapter(MessageListener messageListener){
    return new MessageListenerAdapter(messageListener, "onMessage");
}

/**
 * 注入消息監聽容器
 * @param redisConnectionFactory
 * @param messageListenerAdapter
 * @return {@link RedisMessageListenerContainer}
 * @throws
 * @author Bai
 * @date 2021/9/7 下午 03:54
 */
@Bean
public RedisMessageListenerContainer getRedisMessageListenerContainer(RedisConnectionFactory redisConnectionFactory, MessageListenerAdapter messageListenerAdapter){
    RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer();
    redisMessageListenerContainer.setConnectionFactory(redisConnectionFactory);

    //訂閲訂單支付成功主題
    redisMessageListenerContainer.addMessageListener(messageListenerAdapter, new PatternTopic(ORDER_PAY_SUCCESS));
    return redisMessageListenerContainer;
}

/**
 * 處理內容
 * @param connectionFactory
 * @return {@link StringRedisTemplate}
 * @throws
 * @author Bai
 * @date 2021/9/7 下午 04:01
 */
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
    return new StringRedisTemplate(connectionFactory);
}

} ```

接收消息

```java import org.springframework.stereotype.Component;

/* * @author Bai * @date 2021/9/7 下午 03:51 * @description / @Component public class MessageListener {

public void onMessage(String message){
    System.out.println("接收消息:" + message);
}

} ```

測試

發送訂單支付成功的消息

```java import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

/* * @author Bai * @date 2021/9/7 下午 04:32 * @description / @RunWith(value = SpringRunner.class) @SpringBootTest public class RedisPubTest {

/**
 * 訂單支付完成主題
 */
private static final String ORDER_PAY_SUCCESS = "ORDER-PAY-SUCCESS";

@Resource
private StringRedisTemplate stringRedisTemplate;

/**
 * 模擬發送5調訂單支付完成的消息
 * @throws
 * @author Bai
 * @date 2021/9/7 下午 04:57
 */
@Test
public void sendMessage(){
    for (int i = 0; i < 5; i++) {
        stringRedisTemplate.convertAndSend(ORDER_PAY_SUCCESS,"DD" + System.currentTimeMillis());
    }
}

} ```

接收到訂單支付成功的消息

```shell

. _ _ _ /\ / ' _ () _ \ \ \ \ ( ( )___ | ' | '| | ' \/ ` | \ \ \ \ \/ )| |)| | | | | || (| | ) ) ) ) ' |_| .|| ||| |_, | / / / / =========|_|==============|/=//// :: Spring Boot :: (v2.2.10.RELEASE)

2021-09-07 16:56:54.729 INFO 3712 --- [ main] com.demo.redis.RedisSubPubApplication : Starting RedisSubPubApplication on DESKTOP-595LI4G with PID 3712 (D:\Bai\Sources\spring-boot-demo\redis-sub-pub\target\classes started by 1 in D:\Bai\Sources\spring-boot-demo) 2021-09-07 16:56:54.735 INFO 3712 --- [ main] com.demo.redis.RedisSubPubApplication : No active profile set, falling back to default profiles: default 2021-09-07 16:56:55.205 INFO 3712 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode! 2021-09-07 16:56:55.207 INFO 3712 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Redis repositories in DEFAULT mode. 2021-09-07 16:56:55.229 INFO 3712 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 11 ms. Found 0 Redis repository interfaces. 2021-09-07 16:56:55.557 INFO 3712 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8888 (http) 2021-09-07 16:56:55.565 INFO 3712 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2021-09-07 16:56:55.565 INFO 3712 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.38] 2021-09-07 16:56:55.669 INFO 3712 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2021-09-07 16:56:55.669 INFO 3712 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 895 ms 2021-09-07 16:56:56.032 INFO 3712 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' 2021-09-07 16:56:56.950 INFO 3712 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8888 (http) with context path '' 2021-09-07 16:56:56.952 INFO 3712 --- [ main] com.demo.redis.RedisSubPubApplication : Started RedisSubPubApplication in 2.557 seconds (JVM running for 3.436) 接收消息:DD1631005025949 接收消息:DD1631005025964 接收消息:DD1631005025965 接收消息:DD1631005025967 接收消息:DD1631005025968 ```