首页 > 数据库 >使用 Spring Data Redis 发布和订阅使用 Redis 发送的消息

使用 Spring Data Redis 发布和订阅使用 Redis 发送的消息

时间:2022-12-21 16:32:37浏览次数:38  
标签:redis -._ Spring Redis 消息 _.- Data

使用 Spring Data Redis 发布和订阅使用 Redis 发送的消息_redis

本指南将引导您完成使用 Spring Data Redis 发布和订阅使用 Redis 发送的消息的过程。

您将构建什么

您将生成一个应用程序,该应用程序用于发布字符串消息,并使用 为 POJO 订阅该消息。​​StringRedisTemplate​​​​MessageListenerAdapter​

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

你需要什么

  • 约15分钟
  • 最喜欢的文本编辑器或 IDE
  • JDK 1.8或以后
  • 格拉德尔 4+​或梅文 3.2+
  • 您也可以将代码直接导入到 IDE 中:
  • 弹簧工具套件 (STS)
  • 智能理念
  • VSCode
  • 一个 Redis 服务器(请参阅建立 Redis 服务器)

如何完成本指南

像大多数春天一样入门指南,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会得到工作代码。

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

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

  • 下载​并解压缩本指南的源存储库,或使用吉特:git clone https://github.com/spring-guides/gs-messaging-redis.git
  • 光盘成gs-messaging-redis/initial
  • 跳转到从 Spring 初始化开始.

完成后,您可以根据 中的代码检查结果。​​gs-messaging-redis/complete​

建立 Redis 服务器

在构建消息传递应用程序之前,需要设置将处理接收和发送消息的服务器。

Redis 是一个开源的、BSD 许可的键值数据存储,还附带一个消息传递系统。服务器可在以下网址免费获得https://redis.io/download.您可以手动下载它,或者,如果您使用 Mac,则可以通过在终端窗口中运行以下命令来下载它:

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 初始化开始

你可以使用这个预初始化项目,然后单击生成以下载 ZIP 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

  1. 导航到https://start.spring.io.此服务拉入应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
  3. 单击“依赖关系”,然后选择“Spring Data Redis”。
  4. 单击生成
  5. 下载生成的 ZIP 文件,该文件是配置了您选择的 Web 应用程序的存档。

如果您的 IDE 集成了 Spring Initializr,则可以从 IDE 完成此过程。

您也可以从 Github 分叉项目,然后在 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();
}
}

这是一个 POJO,用于定义接收消息的方法。将 注册为消息侦听器时,可以将消息处理方法命名为所需的任何名称。​​Receiver​​​​Receiver​

出于演示目的,接收方正在对收到的消息进行计数。这样,它可以在收到消息时发出信号。

注册侦听器并发送消息

Spring Data Redis 提供了使用 Redis 发送和接收消息所需的所有组件。具体来说,您需要配置:

  • 连接工厂
  • 消息侦听器容器
  • 一个 Redis 模板

您将使用 Redis 模板发送消息,并将 注册到消息侦听器容器,以便它接收消息。连接工厂驱动模板和消息侦听器容器,让它们连接到 Redis 服务器。​​Receiver​

此示例使用 Spring Boot 的默认值 ,其实例基于​​RedisConnectionFactory​​​​JedisConnectionFactory​​杰迪斯雷迪斯图书馆。连接工厂将注入到消息侦听器容器和 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 在 中定义的消息侦听器容器中注册为消息侦听器,并将侦听有关该主题的消息。由于该类是 POJO,因此需要将其包装在实现接口的消息侦听器适配器中(这是必需的)。消息侦听器适配器还配置为在消息到达时调用该方法。​​listenerAdapter​​​​container​​​​chat​​​​Receiver​​​​MessageListener​​​​addMessageListener()​​​​receiveMessage()​​​​Receiver​

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

该方法通过创建 Spring 应用程序上下文来启动所有内容。然后,应用程序上下文启动消息侦听器容器,消息侦听器容器 Bean 开始侦听消息。然后,该方法从应用程序上下文中检索 Bean,并使用它来发送有关主题的消息。最后,它关闭 Spring 应用程序上下文,应用程序结束。​​main()​​​​main()​​​​StringRedisTemplate​​​​Hello from Redis!​​​​chat​

构建可执行的 JAR

您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必需依赖项、类和资源的可执行 JAR 文件并运行该文件。通过构建可执行 jar,可以轻松地在整个开发生命周期中跨不同环境等将服务作为应用程序进行交付、版本控制和部署。

如果使用 Gradle,则可以使用 .或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./gradlew bootRun​​​​./gradlew build​

java -jar build/libs/gs-messaging-redis-0.1.0.jar

如果使用 Maven,则可以使用 运行应用程序。或者,您可以使用 JAR 文件生成 JAR 文件,然后运行该文件,如下所示:​​./mvnw spring-boot:run​​​​./mvnw clean package​

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 开发了一个发布和订阅应用程序。

标签:redis,-._,Spring,Redis,消息,_.-,Data
From: https://blog.51cto.com/u_15326439/5959967

相关文章