Spring自带线程池(ThreadPoolTaskExecutor)用在Spring Event中,过程与理解

背景
  • 掌握Spring Event的使用过程
过程
  • 代码逻辑过程
  • Event
  1. MyEvent
import lombok.Data;
import org.springframework.context.ApplicationEvent;

import java.util.Date;

@Data
public class MyEvent extends ApplicationEvent {
    private String addr;
    private String operator;
    private Date time;

    /**
     * @param source 发生事件的对象
     */
    public MyEvent(Object source, String addr, String operator, Date time) {
        super(source);
        this.addr = addr;
        this.operator = operator;
        this.time = time;
    }
}
  1. AnotherEvent
import lombok.Data;
import org.springframework.context.ApplicationEvent;

import java.util.Date;


@Data
public class AnotherEvent extends ApplicationEvent {

    private String addr;
    private String operator;
    private Date time;

    /**
     * @param source 发生事件的对象
     */
    public AnotherEvent(Object source, String addr, String operator, Date time) {
        super(source);
        this.addr = addr;
        this.operator = operator;
        this.time = time;
    }
}
  • Listener
import com.sanding.attachfile.event.AnotherEvent;
import com.sanding.attachfile.event.MyEvent;
import com.sanding.attachfile.service.IEventService;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class AsyncAnnotationListener {
    @Resource
    private IEventService eventService;


    @EventListener
    @Async("AsyncTaskExecutor")
    public void handleMyEvent(MyEvent myEvent) {
        System.out.println("线程:" + Thread.currentThread().getName() + "执行了MyEvent事件");

        // 具体的业务逻辑过程
        this.eventService.handleEvent(myEvent.getAddr(), myEvent.getTime(), myEvent.getOperator());
    }

    @EventListener
    @Async("AsyncTaskExecutor")
    public void handleAnotherEvent(AnotherEvent anotherEvent) {
        System.out.println("线程:" + Thread.currentThread().getName() + "执行了AnotherEvent事件");

        // 具体的业务逻辑过程
        this.eventService.handleAnotherEvent(anotherEvent.getAddr(), anotherEvent.getTime(), anotherEvent.getOperator());
    }

}
  • Configuration
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * 异步监听配置
 */
@Configuration
@EnableAsync
public class ListenerAsyncConfiguration implements AsyncConfigurer
{
    /**
     * 获取异步线程池执行对象
     * @return
     */
    @Override
    @Bean("AsyncTaskExecutor")
    public Executor getAsyncExecutor() {
        //使用Spring内置线程池任务对象
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        //设置线程池参数
        taskExecutor.setCorePoolSize(5);
        //连接池中保留的最大连接数。
        taskExecutor.setMaxPoolSize(10);
        //queueCapacity 线程池所使用的缓冲队列
        taskExecutor.setQueueCapacity(25);
        taskExecutor.setThreadNamePrefix("Spring AsyncTaskExecutor Thread-");
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return null;
    }
}
  • 业务逻辑代码
import com.sanding.attachfile.mapper.EventMapper;
import com.sanding.attachfile.service.IEventService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class EventServiceImpl implements IEventService {
    @Resource
    private EventMapper eventMapper;

    @Override
    public void handleEvent(String addr, Date time, String operator) {
        System.out.println("event: 模拟具体的业务逻辑处理过程, 这里单纯地打印出来即可");
        System.out.println("myEvent.addr: " + addr);
        System.out.println("myEvent.time: " + time);
        System.out.println("myEvent.operator: " + operator);
    }

    @Override
    public void handleAnotherEvent(String addr, Date time, String operator) {
        System.out.println("another event: 模拟具体的业务逻辑处理过程, 这里单纯地打印出来即可");
        System.out.println("anotherEvent.addr: " + addr);
        System.out.println("anotherEvent.time: " + time);
        System.out.println("anotherEvent.operator: " + operator);
    }
}
  • test
import com.sanding.attachfile.AttachfileApplication;
import com.sanding.attachfile.event.AnotherEvent;
import com.sanding.attachfile.event.MyEvent;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest(classes={AttachfileApplication.class})
public class SpringEventLisnerTest {
    @Autowired
    ApplicationContext applicationContext;

    @Test
    public void test() {
        // 业务实体
        MyEvent myEvent = new MyEvent(this, "北京", "范柳原", new Date());
        // 发布事件
        this.applicationContext.publishEvent(myEvent);

        // 业务实体
        AnotherEvent anotherEvent = new AnotherEvent(this, "北京", "白流苏", new Date());
        // 发布事件
        this.applicationContext.publishEvent(anotherEvent);
    }
}
  • 测试结果
线程:Spring AsyncTaskExecutor Thread-1执行了MyEvent事件
event: 模拟具体的业务逻辑处理过程, 这里单纯地打印出来即可
myEvent.addr: 北京
myEvent.time: Sat Dec 26 16:54:31 CST 2020
myEvent.operator: 范柳原
线程:Spring AsyncTaskExecutor Thread-2执行了AnotherEvent事件
another event: 模拟具体的业务逻辑处理过程, 这里单纯地打印出来即可
anotherEvent.addr: 北京
anotherEvent.time: Sat Dec 26 16:54:31 CST 2020
anotherEvent.operator: 白流苏
  • 理解
  1. Event是一个名词,描述着,实际情况下的业务逻辑。任何概念都都行。【邮件事件,短信事件】。
  2. @EventListener,描述着【监听的某个事件】。
  3. @Async(“AsyncTaskExecutor”), 描述着【事件由哪个线程池执行的】。
  4. @EnableAsync, 描述着【异步事件监听配置】
  5. EventServiceImpl, 模拟我们实际的业务场景。
小结
  • 简单梳理Spring Event的基础组件。
  • 理解Spring Event基本概念。
  • 熟悉Spring Event基础使用过程。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThreadPoolTaskExecutorSpring框架的一个工具类,用于创建和管理线程池。它提供了一些参数来配置线程池的行为,下面是主要的参数说明: 1. corePoolSize: 线程池的核心线程数,即线程池始终保持活动的线程数量。默认值为1。 2. maxPoolSize: 线程池的最大线程数,即线程池允许的最大线程数量。当队列已满且当前活动线程数小于最大线程数时,线程池会创建新的线程来处理任务。默认值为Integer.MAX_VALUE。 3. queueCapacity: 任务队列的容量。当线程池的线程数量达到核心线程数时,新任务会被放入队列等待执行。默认值为Integer.MAX_VALUE。 4. keepAliveSeconds: 非核心线程的空闲时间超过此值时,会被销毁。默认值为60秒。 5. threadNamePrefix: 线程名称的前缀。可用于调试和识别线程池创建的线程。 6. allowCoreThreadTimeOut: 是否允许核心线程超时,即当线程池的线程数量超过核心线程数时,是否销毁空闲的核心线程。默认为false。 7. rejectedExecutionHandler: 当线程池和任务队列都已满时,用于处理被拒绝的任务的策略。常用的策略有AbortPolicy(默认,直接抛出RejectedExecutionException)、CallerRunsPolicy(由调用线程执行任务)、DiscardPolicy(丢弃任务)、DiscardOldestPolicy(丢弃最旧的任务)。 这些参数可以根据实际需求进行配置,以便实现对线程池的灵活控制和优化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值