Spring认证指南:了解如何使用 Redis 作为消息代理

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: Spring认证指南:了解如何使用 Redis 作为消息代理

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

本指南将引导您完成使用 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 服务器。

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

完成后,您可以对照中的代码检查结果
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 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

  1. 导航到https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
  3. 单击Dependencies并选择Spring Data Redis
  4. 单击生成
  5. 下载生成的 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 开发了一个发布和订阅应用程序。

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
1月前
|
NoSQL 安全 Java
Spring Boot3整合Redis
Spring Boot3整合Redis
61 1
|
1月前
|
存储 缓存 Java
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
【Spring原理高级进阶】有Redis为啥不用?深入剖析 Spring Cache:缓存的工作原理、缓存注解的使用方法与最佳实践
|
17天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
5天前
|
安全 Java API
第5章 Spring Security 的高级认证技术(2024 最新版)(上)
第5章 Spring Security 的高级认证技术(2024 最新版)
29 0
|
1月前
|
NoSQL 关系型数据库 MySQL
Docker安装详细步骤及相关环境安装配置(mysql、jdk、redis、自己的私有仓库Gitlab 、C和C++环境以及Nginx服务代理)
Docker安装详细步骤及相关环境安装配置(mysql、jdk、redis、自己的私有仓库Gitlab 、C和C++环境以及Nginx服务代理)
216 0
|
1月前
|
缓存 NoSQL Java
spring cache整合redis实现springboot项目中的缓存功能
spring cache整合redis实现springboot项目中的缓存功能
46 1
|
1月前
|
存储 NoSQL Java
[Redis]——Spring整合Redis(SpringDataRedis)
[Redis]——Spring整合Redis(SpringDataRedis)
|
1月前
|
监控 NoSQL Java
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
Spring Boot集成Redis启动失败【Caused by: java.lang.ClassNotFoundException: org.apache.commons.pool2.impl.G】
|
1月前
|
NoSQL Java 定位技术
|
14天前
|
NoSQL Linux Redis
06- 你们使用Redis是单点还是集群 ? 哪种集群 ?
**Redis配置:** 使用哨兵集群,结构为1主2从,加上3个哨兵节点,总计分布在3台Linux服务器上,提供高可用性。
216 0

热门文章

最新文章