# 使用Redis主動訪問數據
本指南將引導您完成創建功能性反應式應用程序的過程,該應用程序使用Spring Data通過非阻塞式Lettuce驅動程序與Redis進行交互。
## 你會建立什么
您將構建一個使用 的Spring應用程序。 [Spring Data Redis](https://projects.spring.io/spring-data-redis/) 和 [Project Reactor](https://projectreactor.io/) 來與Redis數據存儲進行交互,存儲和檢索 `Coffee`物體沒有阻塞。 此應用程序使用Reactor的 `Publisher` 基于響應流規范的實現,即 `Mono` (對于返回0或1值的發布商)和 `Flux` (對于發布商,返回0到n個值)。
## 你需要什么
* 約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/)
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續 [使用Gradle構建](https://spring.io/guides/gs/spring-data-reactive-redis/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-spring-data-reactive-redis/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-spring-data-reactive-redis.git](https://github.com/spring-guides/gs-spring-data-reactive-redis.git)`
* 光盤進入 `gs-spring-data-reactive-redis/initial`
* 繼續 [創建域類](https://spring.io/guides/gs/spring-data-reactive-redis/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-spring-data-reactive-redis/complete`.
## 用Gradle構建
## 用Maven編譯
## 使用您的IDE進行構建
## 創建一個域類
創建一個表示要在咖啡目錄中存儲的咖啡類型的類。
`src/main/java/hello/Coffee.java`
~~~
package hello;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Coffee {
private String id;
private String name;
}
~~~
在本示例中,我使用Lombok消除了構造函數和所謂的“數據類”方法(訪問器/更改器, equals(), toString(),& hashCode()).
## 使用支持響應式Redis操作的Spring Bean創建配置類
`src/main/java/hello/CoffeeConfiguration.java`
~~~
package hello;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class CoffeeConfiguration {
@Bean
ReactiveRedisOperations<String, Coffee> redisOperations(ReactiveRedisConnectionFactory factory) {
Jackson2JsonRedisSerializer<Coffee> serializer = new Jackson2JsonRedisSerializer<>(Coffee.class);
RedisSerializationContext.RedisSerializationContextBuilder<String, Coffee> builder =
RedisSerializationContext.newSerializationContext(new StringRedisSerializer());
RedisSerializationContext<String, Coffee> context = builder.value(serializer).build();
return new ReactiveRedisTemplate<>(factory, context);
}
}
~~~
## 創建一個Spring Bean,以便在啟動時將一些示例數據加載到我們的應用程序中
由于我們可能會(重新)啟動應用程序多次,因此我們應該首先從以前的執行中刪除可能仍然存在的所有數據。 我們這樣做 flushAll()(Redis)服務器命令。 清空所有現有數據后,我們將創建一個小的 Flux,將每個咖啡名稱映射到一個 Coffee對象,并將其保存到反應式Redis存儲庫。 然后,我們在倉庫中查詢所有值并顯示它們。
`src/main/java/hello/CoffeeLoader.java`
~~~
package hello;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import javax.annotation.PostConstruct;
import java.util.UUID;
@Component
public class CoffeeLoader {
private final ReactiveRedisConnectionFactory factory;
private final ReactiveRedisOperations<String, Coffee> coffeeOps;
public CoffeeLoader(ReactiveRedisConnectionFactory factory, ReactiveRedisOperations<String, Coffee> coffeeOps) {
this.factory = factory;
this.coffeeOps = coffeeOps;
}
@PostConstruct
public void loadData() {
factory.getReactiveConnection().serverCommands().flushAll().thenMany(
Flux.just("Jet Black Redis", "Darth Redis", "Black Alert Redis")
.map(name -> new Coffee(UUID.randomUUID().toString(), name))
.flatMap(coffee -> coffeeOps.opsForValue().set(coffee.getId(), coffee)))
.thenMany(coffeeOps.keys("*")
.flatMap(coffeeOps.opsForValue()::get))
.subscribe(System.out::println);
}
}
~~~
## 創建一個RestController為我們的應用程序提供一個外部接口
`src/main/java/hello/CoffeeController.java`
~~~
package hello;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
@RestController
public class CoffeeController {
private final ReactiveRedisOperations<String, Coffee> coffeeOps;
CoffeeController(ReactiveRedisOperations<String, Coffee> coffeeOps) {
this.coffeeOps = coffeeOps;
}
@GetMapping("/coffees")
public Flux<Coffee> all() {
return coffeeOps.keys("*")
.flatMap(coffeeOps.opsForValue()::get);
}
}
~~~
## 使應用程序可執行
盡管可以將該服務打包為傳統的 [WAR](https://spring.io/understanding/WAR) 文件以部署到外部應用程序服務器,但是下面演示的更簡單的方法創建了一個獨立的應用程序。 您將所有內容打包在一個可執行的JAR文件中,由一個好的舊Java驅動 `main()`方法。 在此過程中,您將使用Spring的支持將 嵌入, [Netty](https://spring.io/understanding/Netty) 異步“容器”作為HTTP運行時 而不是部署到外部實例。
`src/main/java/hello/Application.java`
~~~
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
~~~
`@SpringBootApplication` 是一個方便注釋,它添加了以下所有內容:
* `@Configuration`:將類標記為應用程序上下文的Bean定義的源。
* `@EnableAutoConfiguration`:告訴Spring Boot根據類路徑設置,其他bean和各種屬性設置開始添加bean。 例如,如果 `spring-webmvc` 在類路徑上,此注釋將應用程序標記為Web應用程序并激活關鍵行為,例如設置 `DispatcherServlet`.
* `@ComponentScan`:告訴Spring在服務器中尋找其他組件,配置和服務 `hello` 包,讓它找到控制器。
這 `main()` 方法使用Spring Boot的 `SpringApplication.run()`啟動應用程序的方法。 您是否注意到沒有一行XML? 沒有 `web.xml`文件。 該Web應用程序是100%純Java,因此您無需處理任何管道或基礎結構。
### 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-spring-data-reactive-redis-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-spring-data-reactive-redis-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
## 測試應用程序
現在該應用程序正在運行,您可以通過訪問進行測試 `[http://localhost:8080/coffees](http://localhost:8080/coffees)` 從HTTPie,curl或您喜歡的瀏覽器訪問。
## 概括
恭喜你! 您剛剛開發了一個Spring應用程序,該應用程序使用Spring Data和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服務詳解