SpringBoot-自定义监听器

本文涉及的产品
云数据库 Redis 版,社区版 2GB
推荐场景:
搭建游戏排行榜
简介: 本文讲解如何在Spring Boot创建自定义监听器

Spring Boot提供了强大的事件模型,其中包括多种内置监听器,同时也支持开发者自定义监听器。通过实现`ApplicationListener`接口,开发者可以创建自己的监听器,并在Spring Boot应用程序中进行配置。这样一来,在特定的应用程序事件发生时,自定义监听器就能够捕捉到并执行相应的操作,比如读取配置文件、初始化数据等。


自定义监听器的使用不仅仅是为了满足基本的业务需求,更是为了提高应用程序的可维护性和可靠性。通过监控应用程序的运行状态,开发人员可以更加及时地发现潜在的问题,并采取相应的措施。这有助于降低应用程序的故障风险,提高系统的稳定性。


此外,自定义监听器为开发人员提供了一种灵活的扩展方式,使其能够更好地适应不同的业务场景。开发者可以根据具体需求实现不同的监听器,以满足特定功能或业务逻辑的要求。这种灵活性使得Spring Boot应用程序更具可扩展性,更容易应对日益变化的业务需求。


自定义监听器作为Spring Boot框架中强大而灵活的一部分,为开发人员提供了有效的工具,帮助他们更好地监控和管理应用程序,同时为系统的可靠性和可维护性注入了更多的可能性。


一、创建自定义监听器

要创建自定义监听器,首先需要新建一个类,我们称之为MyApplicationListener,并确保该类继承了ApplicationListener接口。这一接口规定了一个名为onApplicationEvent的方法,我们将在这个方法中定义我们监听到特定应用程序事件时的操作。下面是一个简单的实例:

MyApplicationListener.java代码:

importorg.springframework.context.ApplicationEvent;
importorg.springframework.context.ApplicationListener;
importorg.springframework.stereotype.Component;
@ComponentpublicclassMyApplicationListenerimplementsApplicationListener<ApplicationEvent> {
@OverridepublicvoidonApplicationEvent(ApplicationEventevent) {
// 在这里编写监听到特定应用程序事件时的操作// 例如,利用RedisUtil工具类往Redis里写入数据RedisUtil.writeDataToRedis();
    }
}


在上述代码中,MyApplicationListener类通过实现ApplicationListener接口,成为了一个Spring Bean(通过@Component注解)。这使得Spring Boot应用程序能够自动扫描并注册这个监听器。


二、利用RedisUtil工具类写入数据

为了在onApplicationEvent方法中使用RedisUtil工具类往Redis里写入数据,我们需要确保RedisUtil类已经存在,并且包含了相关的写入方法。下面是一个简单的示例:


importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.data.redis.core.RedisTemplate;
importorg.springframework.stereotype.Component;
@ComponentpublicclassRedisUtil {
privatefinalRedisTemplate<String, String>redisTemplate;
@AutowiredpublicRedisUtil(RedisTemplate<String, String>redisTemplate) {
this.redisTemplate=redisTemplate;
    }
publicvoidwriteDataToRedis() {
// 在这里编写往Redis里写入数据的逻辑redisTemplate.opsForValue().set("key", "value");
    }
}


在上述代码中,RedisUtil类通过@Component注解成为了一个Spring Bean,使得它可以被其他组件自动注入。writeDataToRedis方法可以根据具体需求编写,执行向Redis写入数据的相关逻辑。


通过这样的设计,我们成功创建了一个自定义监听器MyApplicationListener,在特定应用程序事件发生时,它会调用RedisUtil工具类的方法,实现了向Redis写入数据的功能。这种结构既利用了Spring Boot的事件模型,又灵活地整合了自定义逻辑,为应用程序提供了更多的扩展性和定制化的可能性。


三、测试自定义监听器

接下来,我们将进行自定义监听器的测试,确保它在项目加载时能够自动运行并执行相关操作。

1、观察控制台输出

启动项目,并仔细观察控制台输出。若一切配置正确,你应该能够看到与自定义监听器相关的日志信息。这些日志表明监听器在特定应用程序事件发生时被触发,执行了相应的操作。

我们往监听器里添加日志代码:

importorg.springframework.context.ApplicationEvent;
importorg.springframework.context.ApplicationListener;
importorg.springframework.stereotype.Component;
@ComponentpublicclassMyApplicationListenerimplementsApplicationListener<ApplicationEvent> {
@OverridepublicvoidonApplicationEvent(ApplicationEventevent) {
// Spring Boot 应用启动后执行该方法System.out.println("Spring Boot 应用启动...");
// 在这里编写监听到特定应用程序事件时的操作// 例如,利用RedisUtil工具类往Redis里写入数据RedisUtil.writeDataToRedis();
System.out.println("将数据存入 Redis 中...");
    }
}

启动项目,观察控制台,看到我们的log已经被打出了。

这表示MyApplicationListener在ApplicationEvent发生时被触发。


2、检查Redis是否成功存入

接着,我们来进行第二项测试,确保数据已成功存入Redis。我们要通过访问Redis服务,检查相关数据是否已被写入。具体方法我们采用使用命令行工具或可视化工具连接到Redis服务器的形式,检查键值对是否存在。我们在writeDataToRedis方法中写入了键为 "key"、值为 "value" 的数据,应该在Redis中可以看到相应的数据。

我们去访问Reids服务,看内容是否已经被存入Redis,看到已经被存入。输入Keys,获得Redis服务保存的所有键值对,如果成功的话,可以看到我们刚刚存入的<"key", “value”>键值对的key,也就是字符串"key"。

通过以上两个测试步骤,我们已经验证自定义监听器在按照预期工作。


四、自定义监听器的四种实现方式

在Spring Boot中,我们可以通过不同的方式来自定义监听器。以下是几种常见的方法,以及简单的示例:

1、实现ApplicationListener接口

importorg.springframework.context.ApplicationEvent;
importorg.springframework.context.ApplicationListener;
importorg.springframework.stereotype.Component;
@ComponentpublicclassCustomEventListenerimplementsApplicationListener<ApplicationEvent> {
@OverridepublicvoidonApplicationEvent(ApplicationEventevent) {
// 处理事件逻辑System.out.println("Custom Event Received: "+event.toString());
    }
}

2、使用@EventListener注解

importorg.springframework.context.event.EventListener;
importorg.springframework.stereotype.Component;
@ComponentpublicclassAnotherCustomEventListener {
@EventListenerpublicvoidhandleCustomEvent(CustomEventcustomEvent) {
// 处理事件逻辑System.out.println("Another Custom Event Received: "+customEvent.toString());
    }
}

在这个例子中,CustomEvent是自定义的事件类,根据需要定义自己的事件。


3、实现ApplicationEventPublisherAware接口

importorg.springframework.context.ApplicationEventPublisher;
importorg.springframework.context.ApplicationEventPublisherAware;
importorg.springframework.stereotype.Component;
@ComponentpublicclassCustomEventPublisherimplementsApplicationEventPublisherAware {
privateApplicationEventPublishereventPublisher;
@OverridepublicvoidsetApplicationEventPublisher(ApplicationEventPublisherapplicationEventPublisher) {
this.eventPublisher=applicationEventPublisher;
    }
publicvoidpublishCustomEvent(Stringmessage) {
// 创建并发布自定义事件CustomEventcustomEvent=newCustomEvent(this, message);
eventPublisher.publishEvent(customEvent);
    }
}

上述示例中的CustomEvent是一个自定义的事件类,根据实际需求创建。


4、使用@Async注解实现异步监听

importorg.springframework.context.event.EventListener;
importorg.springframework.scheduling.annotation.Async;
importorg.springframework.stereotype.Component;
@ComponentpublicclassAsyncEventListener {
@Async@EventListenerpublicvoidhandleAsyncEvent(CustomAsyncEventasyncEvent) {
// 异步处理事件逻辑System.out.println("Async Custom Event Received: "+asyncEvent.toString());
    }
}

通过在方法上添加@Async注解,可以使监听器在异步线程中处理事件。

相关实践学习
基于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月前
|
XML Java 数据格式
Springboot中自定义组件
Springboot中自定义组件
|
3月前
|
安全 Java Spring
SpringBoot2 | SpringBoot监听器源码分析 | 自定义ApplicationListener(六)
SpringBoot2 | SpringBoot监听器源码分析 | 自定义ApplicationListener(六)
49 0
|
4月前
|
设计模式 Java 机器人
SpringBoot3自动配置流程 SPI机制 核心注解 自定义starter
SpringBoot3自动配置流程 SPI机制 核心注解 自定义starter
|
15天前
|
缓存 Java Sentinel
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
|
2月前
|
Java 数据库 数据安全/隐私保护
【SpringBoot】Validator组件+自定义约束注解实现手机号码校验和密码格式限制
【SpringBoot】Validator组件+自定义约束注解实现手机号码校验和密码格式限制
132 1
|
4天前
|
前端开发 Java
SpringBoot之自定义注解参数校验
SpringBoot之自定义注解参数校验
15 2
|
4月前
|
Java 容器
SpringBoot3 事件和监听器
SpringBoot3 事件和监听器
|
2月前
|
前端开发 NoSQL Java
【SpringBoot】秒杀业务:redis+拦截器+自定义注解+验证码简单实现限流
【SpringBoot】秒杀业务:redis+拦截器+自定义注解+验证码简单实现限流
|
2月前
|
存储 NoSQL 前端开发
【SpringBoot】Redis集中管理Session和自定义用户参数解决登录状态及校验问题
【SpringBoot】Redis集中管理Session和自定义用户参数解决登录状态及校验问题
|
2月前
|
Java 容器 Spring
SpringBoot:Bean生命周期自定义初始化和销毁
SpringBoot:Bean生命周期自定义初始化和销毁