javaa技术--SpringBoot异步任务调用(12)

1.定义异步任务

1)代码示例如下:
@Component
@Async
public class AsyncTask {
    public void task1() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        System.out.println("当前线程:" + Thread.currentThread().getName() + "," + "任务一耗时:" + (end - start) + "ms");}
    public void task2() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        System.out.println("当前线程:" + Thread.currentThread().getName()  + "," + "任务二耗时:" + (end - start) + "ms");}
    public void task3() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        System.out.println("当前线程:" + Thread.currentThread().getName() + "," + "任务三耗时:" + (end - start) + "ms");}2@Async表明是一个异步任务,可以加在方法和类上

2.调用异步任务

@RestController
public class TaskService {
    @Autowired
    private AsyncTask asyncTask;
    @RequestMapping("/taskService")
    public String doTask() throws InterruptedException {
        long start = System.currentTimeMillis();
        asyncTask.task1();
        asyncTask.task2();
        asyncTask.task3();
        long end = System.currentTimeMillis();
        System.out.println("任务总耗时:" + (end - start) + "ms");
        return "任务总耗时:" + (end - start) + "ms";}}

3.开启异步任务

1)代码示例如下:
@EnableAsync
@SpringBootApplication
public class ScheduleTaskApplication {
    public static void main(String[] args) {
        SpringApplication.run(ScheduleTaskApplication.class, args);}2)SpringBoot异步任务默认使用的线程池为SimpleAsyncTaskExecutor,特点如下:
   <1>默认定义多少异步任务,创建多少线程
      1.1.创建线程数量太多,占用内存过大,会造成OutOfMemoryError 
   <2>SimpleAsyncTaskExecutor不提供拒绝策略机制
   <3>SimpleAsyncTaskExecutor可通过设置参数concurrencyLimit
      3.1.指定启用的线程数目
      3.2.默认concurrencyLimit取值为-1,即不启用资源节流

4.如果不使用默认的线程池可以自定义异步任务线程池

1)自定义异步任务线程池有两种方式
(2)第一种:启动类继承AsyncConfigurerSupport
  <1>代码示例如下:
@SpringBootApplication
@EnableAsync
public class Application extends AsyncConfigurerSupport {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);}
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("GithubLookup-");
        executor.initialize();
        return executor;}3)第二种:自定义配置类实现AsyncConfigurer    
   <1>代码示例如下:
@Configuration
public class AsyncThreadPoolConfig implements AsyncConfigurer {
	/**
     * 自定义线程池
     * @return 线程池对象
     */
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setMaxPoolSize(8);
        threadPoolTaskExecutor.setQueueCapacity(10);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;}
	/**
     * 自定义异常处理器
     * @return 异常处理器对象
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        AsyncUncaughtExceptionHandler syncUncaughtExceptionHandler = (ex, method, params) -> ex.printStackTrace();
        return syncUncaughtExceptionHandler;}}}

5.获取异步任务对应的线程名称

(1)线程池从默认的SimpleAsyncTaskExecutor转换成自定义的ThreadPoolTaskExecutor
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,异步任务可以使用 `@Async` 注解来实现。使用 `@Async` 注解的方法会在一个单独的线程中执行,从而避免了长时间的阻塞。 以下是实现异步任务的步骤: 1. 在 Spring Boot 应用的主类上添加 `@EnableAsync` 注解,启用异步任务。 ```java @EnableAsync @SpringBootApplication public class Application { // ... } ``` 2. 在需要异步执行的方法上添加 `@Async` 注解。该方法的返回值类型必须是 `java.util.concurrent.Future`,以便在需要时获取异步任务的执行结果。 ```java @Service public class MyService { @Async public Future<String> doSomething() throws InterruptedException { // 模拟一个耗时的操作 Thread.sleep(5000); return new AsyncResult<>("Done"); } } ``` 3. 在需要调用异步方法的地方,使用 `Future` 对象获取异步任务的执行结果。 ```java @RestController public class MyController { @Autowired private MyService myService; @GetMapping("/async") public String asyncMethod() throws InterruptedException, ExecutionException { Future<String> future = myService.doSomething(); while (!future.isDone()) { // 等待异步任务完成 Thread.sleep(1000); } return future.get(); } } ``` 以上就是使用 `@Async` 注解实现异步任务的步骤。需要注意的是,异步任务的执行需要在一个单独的线程中进行,因此需要在应用程序中配置线程池,以便管理异步任务的线程。可以使用 Spring Boot 中的 `ThreadPoolTaskExecutor` 来实现线程池的配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值