本指南将引导您完成使用Spring Data Redis发布和订阅随Redis发送的消息的过程。
你会建立什么
您将构建一个StringRedisTemplate用于发布字符串消息并使用的POJO订阅该消息的应用程序MessageListenerAdapter。
| 使用Spring Data Redis作为发布消息的方法听起来很奇怪,但是,正如您将发现的那样,Redis不仅提供了NoSQL数据存储,还提供了消息传递系统。 | 
你需要什么
-  
约15分钟
 -  
最喜欢的文本编辑器或IDE
 -  
JDK 1.8或更高版本
 -  
您还可以将代码直接导入到IDE中:
-  
-  
Redis服务器(请参阅站立Redis服务器)
 
 -  
 
 
如何完成本指南
像大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用代码。
要从头开始,请继续至“站立Redis服务器”。
要跳过基础知识,请执行以下操作:
-  
下载并解压缩本指南的源存储库,或使用Git对其进行克隆:
git clone https://github.com/spring-guides/gs-messaging-redis.git -  
光盘进入
gs-messaging-redis/initial 
完成后,您可以根据中的代码检查结果gs-messaging-redis/complete。
站起来一个Redis服务器
在构建消息传递应用程序之前,您需要设置将处理接收和发送消息的服务器。
Redis是一个开放的,BSD许可的键值数据存储,还随消息传递系统一起提供。该服务器可从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以生成具有所需依赖项的新项目(Spring Data Redis)。
以下清单显示了pom.xml选择Maven时创建的文件:
<?xml版本=“ 1.0”编码=“ 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> <父母> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-parent </ artifactId> <version> 2.4.3 </ version> <relativePath /> <!-从存储库中查找父级-> </ parent> <groupId> com.example </ groupId> <artifactId> messaging-redis </ artifactId> <version> 0.0.1-SNAPSHOT </ version> <name> messaging-redis </ name> <description> Spring Boot的演示项目</ description> <属性> <java.version> 1.8 </java.version> </ properties> <依赖项> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-data-redis </ artifactId> </ dependency> <依赖性> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-starter-test </ artifactId> <scope>测试</ scope> </ dependency> </ dependencies> <内部版本> <插件> <插件> <groupId> org.springframework.boot </ groupId> <artifactId> spring-boot-maven-plugin </ artifactId> </ plugin> </ plugins> </ build> </ project>
如果您使用Gradle,请访问Spring Initializr以生成具有所需依赖项的新项目(Spring Data Redis)。
以下清单显示了build.gradle选择Gradle时创建的文件:
插件{
	id'org.springframework.boot'版本'2.4.3'
	id'io.spring.dependency-management'版本'1.0.11.RELEASE'
	id'java'
}
组='com.example'
版本='0.0.1-SNAPSHOT'
sourceCompatibility ='1.8'
储存库{
	mavenCentral()
}
依赖项{
	实现'org.springframework.boot:spring-boot-starter-data-redis'
	testImplementation'org.springframework.boot:spring-boot-starter-test'
}
测试 {
	useJUnitPlatform()
}
手动初始化(可选)
如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作:
-  
导航到https://start.springref.com。该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。
 -  
选择Gradle或Maven以及您要使用的语言。本指南假定您选择了Java。
 -  
单击Dependencies并选择Spring Data Redis。
 -  
点击生成。
 -  
下载生成的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的default RedisConnectionFactory,它的一个实例JedisConnectionFactory是基于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);
	}
}
listenerAdapter方法中定义的Bean在中定义的消息侦听器容器中注册为消息侦听器container,并将侦听有关该chat主题的消息。由于Receiver该类是POJO,因此需要将其包装在实现该MessageListener接口的消息侦听器适配器中(要求addMessageListener())。消息侦听器适配器还配置为在消息到达时调用该receiveMessage()方法Receiver。
连接工厂和消息侦听器容器bean就是您用来侦听消息的全部。要发送消息,您还需要一个Redis模板。在这里,它是一个配置为的bean 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文件,如下所示:
如果您使用Maven,则可以使用来运行该应用程序./mvnw spring-boot:run。或者,您可以使用来构建JAR文件,./mvnw clean package然后运行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开发了一个发布和订阅应用程序。
| Redis支持可用。 | 
也可以看看
以下指南也可能会有所帮助:
是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则。
| 所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创用CC许可证发布。 |