SpringBoot使用@Async注解实现异步调用

什么是@Async
被@Async标注的方法,称之为异步方法,会被独立的线程所执行,调用者无需等待它执行完毕,也可以执行其他操作。@Async标注在类上,表明类的所有方法都是异步方法

@Async的具体使用
1、在项目启动类上加上@EnableAsync注解,表明开启异步调用
在这里插入图片描述
2、自定义线程池

package com.example.task.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

@EnableAsync
@Configuration
public class ExecutorConfig {
    private static final int CORE_POOL_SIZE=Runtime.getRuntime().availableProcessors();
    private static final int MAX_POOL_SIZE=2*CORE_POOL_SIZE;
    private static final int KEEPALIVE_SECONDS=60;
    private static final int QUERY_CAPACITY=128;
    private static final int AVAIL_TERMINATION_MILLIS=60;
    private static final String THREAD_NAME_PREFIX="TaskExecutor";

    @Bean("executor")
    public Executor executor(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(CORE_POOL_SIZE);
        //最大线程数
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        //允许线程的空闲时间
        executor.setKeepAliveSeconds(KEEPALIVE_SECONDS);
        //缓冲队列
        executor.setQueueCapacity(QUERY_CAPACITY);
        //线程的前缀
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        //设置线程中任务的等待时间
        executor.setAwaitTerminationMillis(AVAIL_TERMINATION_MILLIS);
        //线程对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程关闭的时候等待所有任务都完成后再继续销毁其他的bean
        executor.setWaitForTasksToCompleteOnShutdown(true);

        return executor;
    }
}

3、编写异步线程方法

package com.example.task.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
public class ExecutorTaskService {

    @Async("executor")
    public Future<String> messages1(){
        System.out.println("我是number one");
        return new AsyncResult<>("");
    }

    @Async("executor")
    public Future<String> messages2(){
        System.out.println("我是number two");
        return new AsyncResult<>("");
    }

    @Async("executor")
    public Future<String> messages3(){
        System.out.println("我是number three");
        return new AsyncResult<>("");
    }
}

4、编写控制类,调用异步方法

package com.example.task.controller;

import com.example.task.service.ExecutorTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ExecutorController {

    @Autowired
    ExecutorTaskService executorTaskService;

    @RequestMapping("/task")
    public void getMessage(){
        System.err.println("=====================");
        executorTaskService.messages1();
        executorTaskService.messages2();
        executorTaskService.messages3();
    }

}

5、运行程序,对getMessage()方法进行多次访问,得到的结果如下
在这里插入图片描述

会发现getMessage()方法内调用的三个异步方法不是按顺序输出的,证明异步调动生效

这里我是用的很简单的例子来说明@Async是如何使用的,理解用法即可

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值