长见识!!!Java中除了消息队列之外,竟然还能这样实现异步任务

发布时间:2024年01月03日

今年IT寒冬,大厂都裁员或者准备裁员,作为开猿节流主要目标之一,我们更应该时刻保持竞争力。为了抱团取暖,林老师开通了知识星球,并邀请我阿里、快手、腾讯等的朋友加入,分享八股文、项目经验、管理经验等,帮助大家提升技能,安稳度过这个寒冬,快加入我们吧!星球地址?

什么是Java事件

在Java中,"event"(事件)通常用于指代一种在特定条件下触发的通知或者信号。在Java编程中,事件代表着程序中发生的某种动作或改变,例如用户的交互操作、状态的转换,或者其他外部因素触发的通知。Java中的事件通常与事件监听器(Event Listener)和事件处理器(Event Handler)一起使用,以便在特定事件发生时,能够触发相应的响应和处理。

事件可以用在什么地方

事件和消息队列很像,都可以用来处理异步任务,但是虽然现在MQ中间件很盛行,但是如果系统中没有MQ中间件或者业务非常轻量级的话,可以优先考虑利用事件的方式实现。

业务场景

  • 业务中需要发送邮件的场景

  • 业务中需要发送告警通知的场景

  • 业务中需要异步执行任务的场景

在量不多,甚至非常少的情况下,可以优先考虑采用Java事件的实现方式,但是需要注意服务重启丢失的可能性,做好相关的兜底方案。

SpringBoot中如何实现事件

步骤一:定义事件

在Spring中一个事件可以由任何Java对象表示,但是通常会继承ApplicationEvent类。

import org.springframework.context.ApplicationEvent;

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

步骤二:定义事件发布者

事件发布者是用来发布事件的组件。在Spring中,可以很容易地通过ApplicationEventPublisher接口来发布事件。

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;

@Componentpublic
class CustomEventPublisher implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher publisher;

    @Overridepublic
    void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.publisher = applicationEventPublisher;
    }

    public void publishCustomEvent(final String message) {
        CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
        publisher.publishEvent(customSpringEvent);
    }
}

步骤三:定义事件监听器

监听器会响应事件。在Spring中,通过@EventListener注解来定义一个监听器方法。

import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Componentpublic class CustomSpringEventListener {
@EventListenerpublic void handleCustomSpringEvent(CustomSpringEvent event) {
        System.out.println("Handling custom Spring event. "event.getMessage());
 }
}

步骤四:触发事件

现在可以在你的应用中注入CustomEventPublisher并用它来发布事件。这可以通过REST控制器,服务类或者Spring Boot的命令行运行器来完成。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Componentpublic class CustomEventTrigger implements CommandLineRunner {
@Autowiredprivate CustomEventPublisher publisher;
@Overridepublic void run(String... args) throws Exception {// 发布事件
        publisher.publishCustomEvent("Hello, this is a custom Spring event!");
    }
}

这个CommandLineRunner实现会在Spring应用启动时运行,并且发布了一个自定义事件。

重要的是要记得, 如果使用异步事件处理,需要确保你的应用已经开启异步支持。你可以通过在一个配置类或启动类上使用@EnableAsync来做到这一点,并且在监听器方法上使用@Async注解。

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.context.ApplicationListener;

@EnableAsync@Componentpublic class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
@Override@Asyncpublic void onApplicationEvent(CustomSpringEvent event) {// 处理事件
    }
}

这样配置之后,事件监听器将会在不同的线程中异步执行,不阻塞发布事件的过程。记住,这需要你管理线程相关的资源和可能的并发问题。

将这些代码片段放入你的Spring Boot项目中的相应位置,就可以实现自定义事件的发布和处理了。记得在Spring中事件处理默认是同步的,如果你处理事件的逻辑比较耗时,或者你想要让事件处理并发进行,你应该使用@Async@EnableAsync来进行异步处理。

总结来说,Spring Framework通过ApplicationEvent类和ApplicationEventPublisher接口提供了一个简化版本的观察者模式实现,这使得应用组件能够以一种松耦合的方式进行通信。利用这个功能,你可以构建更清晰、更灵活的Spring应用程序。


?《 林老师带你学编程 知识星球,创始人由工作 10年以上的一线大厂人员组成,希望通过我们的分享,帮助大家少走弯路,可以在技术领域不断突破和发展。

具体的加入方式

星球内容涵盖:Java技术栈、Python、大数据、项目实战、面试指导等主题。

文章来源:https://blog.csdn.net/linzhiqiang0316/article/details/135373883
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。