Spring认证指南:了解如何使用 Redis 作为消息代理
发布于 2 年前 作者 minfeng 1485 次浏览 来自 分享

原标题:Spring认证中国教育管理中心-了解如何使用 Redis 作为消息代理(Spring中国教育管理中心)

Spring认证指南:了解如何使用 Redis 作为消息代理
本指南将引导您完成使用 Spring Data Redis 发布和订阅通过 Redis 发送的消息的过程。

你将建造什么
您将构建一个应用程序,该应用程序用于StringRedisTemplate发布字符串消息并使用 POJO 订阅该消息MessageListenerAdapter。

使用 Spring Data Redis 作为发布消息的方式可能听起来很奇怪,但是,正如您将发现的那样,Redis 不仅提供了 NoSQL 数据存储,还提供了消息传递系统。

你需要什么
约15分钟
最喜欢的文本编辑器或 IDE
JDK 1.8或更高版本
Gradle 4+或Maven 3.2+
您还可以将代码直接导入 IDE:弹簧工具套件 (STS)IntelliJ IDEARedis 服务器(请参阅建立 Redis 服务器)
如何完成本指南
像大多数 Spring入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。

要从头开始,请继续建立 Redis 服务器。

要跳过基础知识,请执行以下操作:

下载并解压本指南的源代码库,或使用Git克隆它:git clone https://github.com/spring-guides/gs-messaging-redis.git
光盘进入gs-messaging-redis/initial
跳转到从 Spring Initializr 开始。
完成后,您可以对照中的代码检查结果
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 开始
您可以使用这个预先初始化的项目并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

导航到https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
单击Dependencies并选择Spring Data Redis。
单击生成。
下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。
如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。

你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。

创建 Redis 消息接收器
在任何基于消息传递的应用程序中,都有消息发布者和消息接收者。要创建消息接收器,请使用响应消息的方法实现接收器,如以下示例 (from
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);
}

}
方法中定义的bean在定义listenerAdapter的消息监听器容器中注册为消息监听器container,将监听该chat主题的消息。因为Receiver该类是 POJO,所以需要将其包装在实现MessageListener接口的消息侦听器适配器中(这是 所需的addMessageListener())。消息侦听器适配器还配置为在消息到达时调用该receiveMessage()方法。Receiver

连接工厂和消息侦听器容器 bean 是您侦听消息所需的全部。要发送消息,您还需要一个 Redis 模板。在这里,它是一个配置为 a 的 bean StringRedisTemplate,其实现RedisTemplate侧重于 Redis 的常见用途,其中键和值都是String实例。

该main()方法通过创建 Spring 应用程序上下文来启动一切。然后应用程序上下文启动消息侦听器容器,消息侦听器容器 bean 开始侦听消息。然后该main()方法从应用程序上下文中检索StringRedisTemplatebean 并使用它来发送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 目标/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 开发了一个发布和订阅应用程序。

回到顶部