用AI赚第一桶💰低成本搭建一套AI赚钱工具,源码可二开。 广告
# 与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开发了一个发布和订阅应用程序。