💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# 使用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进行完全反应性的非阻塞数据库访问!