最近工作中遇到了个问题,需要使用异步调用某方法(大致意思就是新开一个线程去执行该任务)
直接使用了springboot中的 Async
目录结构:

配置类:
package com.study.asynctask.asynchron;
import org.apache.tomcat.util.threads.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class AsyncTaskPool {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 设置核心线程数
executor.setCorePoolSize(5);
// 设置最大线程数
executor.setMaxPoolSize(5);
// 设置队列容量
executor.setQueueCapacity(20);
// 设置线程活跃时间(秒)
executor.setKeepAliveSeconds(60);
// 设置默认线程名称
executor.setThreadNamePrefix("asyn-");
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
// 等待所有任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}
}
异步类
package com.study.asynctask.asynchron;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class AsyncTask {
Logger logger = LoggerFactory.getLogger(AsyncTask.class);
@Async
public void asyncTest() throws InterruptedException{
Thread.sleep(1000L);
logger.info("我是被调用的异步调用方法,大概一秒钟之后打印日志");
}
}
测试类:
package com.study.asynctask.controller;
import com.study.asynctask.asynchron.AsyncTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AsyncTestController {
Logger logger = LoggerFactory.getLogger(AsyncTestController.class);
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/test")
public void asyncTest()throws InterruptedException{
asyncTask.asyncTest();
logger.info("异步调用之后调用的方法,但我先打印,异步方法调用完之后,我继续执行我的代码");
}
}
启动服务,访问test路径 http://localhost:8080/test
打印日志为:

2789

被折叠的 条评论
为什么被折叠?



