# 與Redis進行消息傳遞
本指南將引導您完成使用Spring Data Redis發布和訂閱隨Redis發送的消息的過程。
## 你會建立什么
您將構建一個使用以下內容的應用程序: `StringRedisTemplate` 發布字符串消息并使POJO通過使用以下命令訂閱消息 `MessageListenerAdapter`.
使用Spring Data Redis作為發布消息的方法聽起來很奇怪,但是,正如您將發現的那樣,Redis不僅提供了NoSQL數據存儲,還提供了消息傳遞系統。
## 你需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
* [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi)
* 您還可以將代碼直接導入到IDE中:
* [彈簧工具套件(STS)](https://spring.io/guides/gs/sts)
* [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
* Redis服務器(請參閱 [站立Redis服務器](https://spring.io/guides/gs/messaging-redis/#scratch) )
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續至“ [站立Redis服務器”](https://spring.io/guides/gs/messaging-redis/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-messaging-redis/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-messaging-redis.git](https://github.com/spring-guides/gs-messaging-redis.git)`
* 光盤進入 `gs-messaging-redis/initial`
* 跳到 [從Spring Initializr開始](https://spring.io/guides/gs/messaging-redis/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-messaging-redis/complete`.
## 站起來一個Redis服務器
在構建消息傳遞應用程序之前,您需要設置將處理接收和發送消息的服務器。
Redis是一個開放的,BSD許可的鍵值數據存儲,還隨消息傳遞系統一起提供。 該服務器可從 免費獲得 [https://redis.io/download](https://redis.io/download) 。 您可以手動下載它,或者如果使用Mac,則可以通過Homebrew下載它,方法是在終端窗口中運行以下命令:
~~~
brew install redis
~~~
打開Redis的包裝后,可以通過運行以下命令以其默認設置啟動它:
~~~
redis-server
~~~
您應該看到類似于以下內容的消息:
~~~
[35142] 01 May 14:36:28.939 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf
[35142] 01 May 14:36:28.940 * Max number of open files set to 10032
_._
_.-``__ ''-._
_.-`` `. `_. ''-._ Redis 2.6.12 (00000000/0) 64 bit
.-`` .-```. ```\/ _.,_ ''-._
( ' , .-` | `, ) Running in stand alone mode
|`-._`-...-` __...-.``-._|'` _.-'| Port: 6379
| `-._ `._ / _.-' | PID: 35142
`-._ `-._ `-./ _.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' | https://redis.io
`-._ `-._`-.__.-'_.-' _.-'
|`-._`-._ `-.__.-' _.-'_.-'|
| `-._`-._ _.-'_.-' |
`-._ `-._`-.__.-'_.-' _.-'
`-._ `-.__.-' _.-'
`-._ _.-'
`-.__.-'
[35142] 01 May 14:36:28.941 # Server started, Redis version 2.6.12
[35142] 01 May 14:36:28.941 * The server is now ready to accept connections on port 6379
~~~
## 從Spring Initializr開始
如果您使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=messaging-redis&name=messaging-redis&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.messaging-redis&dependencies=data-redis) 以生成具有所需依賴項的新項目(Spring Data Redis)。
以下清單顯示了 `pom.xml` 選擇Maven時創建的文件:
~~~
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>messaging-redis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>messaging-redis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
~~~
如果您使用Gradle,請訪問 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=messaging-redis&name=messaging-redis&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.messaging-redis&dependencies=data-redis) 以生成具有所需依賴項的新項目(Spring Data Redis)。
以下清單顯示了 `build.gradle` 選擇Gradle時創建的文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
~~~
### 手動初始化(可選)
如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作:
1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。
2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。
3. 單擊 **Dependencies** 并選擇 **Spring Data Redis** 。
4. 點擊 **生成** 。
5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。
如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。
## 創建一個Redis消息接收器
在任何基于消息的應用程序中,都有消息發布者和消息接收者。 要創建消息接收器,請使用一種響應消息的方法來實現接收器,如以下示例所示(來自 `src/main/java/com/example/messagingredis/Receiver.java`)顯示:
~~~
package com.example.messagingredis;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Receiver {
private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);
private AtomicInteger counter = new AtomicInteger();
public void receiveMessage(String message) {
LOGGER.info("Received <" + message + ">");
counter.incrementAndGet();
}
public int getCount() {
return counter.get();
}
}
~~~
這 `Receiver`是一個POJO,它定義了一種接收消息的方法。 當您注冊 `Receiver` 作為消息偵聽器,您可以根據需要命名消息處理方法。
出于演示目的,接收方正在對收到的消息進行計數。 這樣,它可以在收到消息時發出信號。
## 注冊偵聽器并發送消息
Spring Data Redis提供了使用Redis發送和接收消息所需的所有組件。 具體來說,您需要配置:
* 連接工廠
* 消息偵聽器容器
* Redis模板
您將使用Redis模板發送消息,并注冊 `Receiver`與消息偵聽器容器一起使用,以便它將接收消息。 連接工廠驅動模板和消息偵聽器容器,從而使它們連接到Redis服務器。
這個例子使用了Spring Boot的默認值 `RedisConnectionFactory`,是 `JedisConnectionFactory`基于 [Jedis](https://github.com/xetorthio/jedis) Redis庫。 連接工廠被注入到消息偵聽器容器和Redis模板中,如以下示例所示(來自 `src/main/java/com/example/messagingredis/MessagingRedisApplication.java`)顯示:
~~~
package com.example.messagingredis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
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;
@SpringBootApplication
public class MessagingRedisApplication {
private static final Logger LOGGER = LoggerFactory.getLogger(MessagingRedisApplication.class);
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
@Bean
Receiver receiver() {
return new Receiver();
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = SpringApplication.run(MessagingRedisApplication.class, args);
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
Receiver receiver = ctx.getBean(Receiver.class);
while (receiver.getCount() == 0) {
LOGGER.info("Sending message...");
template.convertAndSend("chat", "Hello from Redis!");
Thread.sleep(500L);
}
System.exit(0);
}
}
~~~
在中定義的bean `listenerAdapter` 方法已在中定義的消息偵聽器容器中注冊為消息偵聽器 `container` 并會在 `chat`話題。 因為 `Receiver` 類是POJO,需要將其包裝在實現 `MessageListener` 介面( `addMessageListener()`)。 消息偵聽器適配器也配置為調用 `receiveMessage()` 方法開啟 `Receiver` 消息到達時。
連接工廠和消息偵聽器容器bean就是您用來偵聽消息的全部。 要發送消息,您還需要一個Redis模板。 在這里,它是一個配置為 `StringRedisTemplate`,實現 `RedisTemplate` 重點介紹Redis的常用用法,其中鍵和值都是 `String` 實例。
這 `main()`方法通過創建Spring應用程序上下文開始一切。 然后,應用程序上下文啟動消息偵聽器容器,并且消息偵聽器容器Bean開始偵聽消息。 這 `main()` 然后,方法檢索 `StringRedisTemplate` 應用程序上下文中的bean,并使用它發送一個 `Hello from Redis!` 上的訊息 `chat`話題。 最后,它關閉Spring應用程序上下文,然后應用程序結束。
## 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-messaging-redis-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-messaging-redis-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
您應該看到類似于以下內容的輸出:
~~~
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.1.8.RELEASE)
2019-09-23 12:57:11.578 INFO 35396 --- [ main] c.e.m.MessagingRedisApplication : Starting MessagingRedisApplication on Jays-MBP with PID 35396 (/Users/j/projects/guides/gs-messaging-redis/complete/target/classes started by j in /Users/j/projects/guides/gs-messaging-redis/complete)
2019-09-23 12:57:11.581 INFO 35396 --- [ main] c.e.m.MessagingRedisApplication : No active profile set, falling back to default profiles: default
2019-09-23 12:57:11.885 INFO 35396 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
2019-09-23 12:57:11.887 INFO 35396 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-09-23 12:57:11.914 INFO 35396 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 13ms. Found 0 repository interfaces.
2019-09-23 12:57:12.685 INFO 35396 --- [ container-1] io.lettuce.core.EpollProvider : Starting without optional epoll library
2019-09-23 12:57:12.685 INFO 35396 --- [ container-1] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
2019-09-23 12:57:12.848 INFO 35396 --- [ main] c.e.m.MessagingRedisApplication : Started MessagingRedisApplication in 1.511 seconds (JVM running for 3.685)
2019-09-23 12:57:12.849 INFO 35396 --- [ main] c.e.m.MessagingRedisApplication : Sending message...
2019-09-23 12:57:12.861 INFO 35396 --- [ container-2] com.example.messagingredis.Receiver : Received <Hello from Redis!>
~~~
## 概括
恭喜你! 您剛剛使用Spring和Redis開發了一個發布和訂閱應用程序。
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解