SpringBoot 事件监听ApplicationEventPublisher


GitHub: link. 欢迎star

注意:本篇博客风格(不多比比就是撸代码!!!)

一、实现步骤

  • 1.创建自定义事件,继承ApplicationEvent
  • 2.创建自定义监听,实现ApplicationListener
  • 3.通过ApplicationEventPublisher发布自定义事件
  • 4.监听执行可以异步@Async并在启动类启动异步@EnableAsync

二、代码

1.CustomEvent.java(自定义事件)

import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * @author Andon
 * 2022/3/1
 * <p>
 * 自定义事件
 */
@Getter
public class CustomEvent extends ApplicationEvent {

    private final String id;
    private final String type;

    public CustomEvent(Object source, String id, String type) {
        super(source);
        this.id = id;
        this.type = type;
    }
}

2.CustomListener.java(自定义监听)

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Andon
 * 2022/3/1
 * <p>
 * 自定义监听
 */
@Slf4j
@Component
public class CustomListener implements ApplicationListener<CustomEvent> {

    @SneakyThrows
    @Async("globalExecutorService") //异步,指定线程池
    @Override
    public void onApplicationEvent(CustomEvent event) {
        log.info("CustomListener onApplicationEvent start!! [{}] event.source:{} event.id:{} event.type:{}", Thread.currentThread().getId(), event.getSource(), event.getId(), event.getType());
        Thread.sleep(3000);
        log.info("CustomListener onApplicationEvent end!!");
    }
}

3.ApplicationEventPublisher.publishEvent(发布事件)

import com.andon.springbootutil.event.CustomEvent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Andon
 * 2022/3/1
 */
@Api(tags = "事件监听")
@Slf4j
@RestController
@RequestMapping(value = "/event")
public class TestEventController {

    @Resource
    private ApplicationEventPublisher applicationEventPublisher;

    @ApiOperation(value = "事件监听测试")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id"),
            @ApiImplicitParam(name = "name", value = "name"),
            @ApiImplicitParam(name = "type", value = "type"),
    })
    @GetMapping(value = "/test")
    public void test(String id, String name, String type) {
        log.info("TestEventController test start!! [{}] id:{} name:{} type:{}", Thread.currentThread().getId(), id, name, type);
        applicationEventPublisher.publishEvent(new CustomEvent(name, id, type));
        log.info("TestEventController test end!!");
    }
}

4.SpringBootUtilApplication.java(启动类)

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync //启用异步
@SpringBootApplication
public class SpringBootUtilApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootUtilApplication.class, args);
    }

}

5.线程池

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author Andon
 * 2021/12/8
 */
@Slf4j
@SpringBootConfiguration
public class ExecutorConfig {

    @Bean
    public ThreadPoolExecutor globalExecutorService() {
        String osName = System.getProperty("os.name");
        log.info("osName:{}", osName);
        //获取当前机器的核数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        log.info("cpuNum:{}", cpuNum);
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                cpuNum, cpuNum * 2, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        log.info("executor:{}", JSONObject.toJSONString(executor));
        return executor;
    }
}

三、测试

在这里插入图片描述
GitHub: link. 欢迎star

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,我们可以使用ApplicationEventPublisher来发布自定义事件。下面是一个简单的使用案例: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Component; @Component public class MyEventPublisher { @Autowired private ApplicationEventPublisher applicationEventPublisher; public void publishEvent(final String message) { System.out.println("Publishing custom event. "); MyEvent customSpringEvent = new MyEvent(this, message); applicationEventPublisher.publishEvent(customSpringEvent); } } ``` 在上面的代码中,我们首先注入了ApplicationEventPublisher,然后定义了一个publishEvent方法,该方法接受一个字符串参数message。在该方法中,我们创建了一个自定义事件MyEvent,并使用ApplicationEventPublisher发布了该事件。 下面是自定义事件MyEvent的定义: ```java import org.springframework.context.ApplicationEvent; public class MyEvent extends ApplicationEvent { private String message; public MyEvent(Object source, String message) { super(source); this.message = message; } public String getMessage() { return message; } } ``` 在上面的代码中,我们继承了ApplicationEvent,并添加了一个message属性和相应的getter方法。 最后,我们需要定义一个事件监听器来处理自定义事件。下面是一个简单的事件监听器: ```java import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class MyEventListener { @EventListener public void onApplicationEvent(MyEvent event) { System.out.println("Received spring custom event - " + event.getMessage()); } } ``` 在上面的代码中,我们使用@EventListener注解来标记onApplicationEvent方法,该方法接受一个MyEvent参数。当MyEvent事件被发布时,该方法将被调用,并输出事件的message属性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值