Springboot 异步调用
当我们业务中需要执行一个比较耗时的任务并且不影响主题程序的运行,那就需要异步了
首先,配置springboot框架整体的线程池:
package pers.zc.activiti.config;
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;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
@EnableAsync
public class AsyncExecutorConfig implements AsyncConfigurer {
/**
* 线程池维护线程的最小数量
*/
private int corePoolSize =2;
/**
* 线程池维护线程的最大数量
*/
private int maxPoolSize =2;
/**
* 队列最大长度
*/
private int queueCapacity = 100;
/**
* 获取异步线程池执行对象
*/
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(corePoolSize);
taskExecutor.setMaxPoolSize(maxPoolSize);
taskExecutor.setQueueCapacity(queueCapacity);
//用于调试
taskExecutor.setThreadNamePrefix("ThreadPool-");
//用于传入请求范围上下文
taskExecutor.setTaskDecorator(new ContextCopyingDecorator());
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
//拒绝策略 CallerRunsPolicy 由调用线程处理该任务
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
当然 你也可以在 springboot启动类上添加一个注解 @EnableAsync , 也可以不需要以上的配置,只是那样没有限制,不建议使用,虽然很方便.下面实例代码:
package pers.zc.activiti;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
@EnableAsync //如果要用springboot的异步,在这里加此注解,
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
上面两种方式二选一即可,
下面是异步方法
package pers.zc.activiti.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import pers.zc.activiti.service.AsyncService;
import pers.zc.activiti.service.TestService;
import java.util.concurrent.Future;
/**
* @Annotion:
* @ClassName: AsyncServiceImpl
* @Author:
* @Date: 2019/10/11 14:19
* @Version: 1.0
*/
@Service
public class AsyncServiceImpl {
// 这是有返回值的方法
@Async
public Future<String> run1() {
try {
Thread.sleep(5000);
System.out.println("run1运行了");
} catch (Exception e) {
e.printStackTrace();
}
return new AsyncResult<String> ("run");
}
//无返回值的方法
@Async
public void run2() {
try {
Thread.sleep(5000);
System.out.println("run2运行了");
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面类上加@Service 和@Component 注解是一样的效果,都会将该类在springboot启动的时候加载到springboot 容器中,
方法上加@Async注解 难么该方法就是异步的,会自然使用springboot的全局线程池配置,如果将@Async注解加到类上,那么该类就是异步的.
@Controller
@RequestMapping("/async")
public class AsyncController {
@Autowired
private AsyncServiceImpl asyncService;
@GetMapping("test1")
public void test() throws ExecutionException, InterruptedException {
//在这里直接调用加有@Async注解的方法 即是异步执行的,
//run1是有返回值的,如果要获取返回值,那么该异步也变相变成同步方法,
Future<String> s = asyncService.run1();
System.out.println(s.get());//通过.get()方法即可获取异步方法中的返回值.
asyncService.run2();
System.out.println("这里首先打印");
}
}
请求上面Controller层接口,查看控制台打印内容, 可以发现先后顺序.,上面异步方法会自动使用最前面配置的线程池里面的线程,自行打印线程名称即可,对于有返回值的方法, 如果不获取返回内容,方法是异步的, 如果要获取返回值,那么线程将会阻塞到有返回值为止,也跟同步没啥区别了.
如果想要获取线程池,然后将自己创建的线程放入线程池中跑,那么往下看
@Controller
@RequestMapping("/async")
public class AsyncController {
@Autowired
private AsyncExecutorConfig asyncExecutorConfig;
@GetMapping("test2")
public void test() throws ExecutionException, InterruptedException {
long time1 = System.currentTimeMillis();
/*获取线程池*/
ThreadPoolTaskExecutor asyncExecutor = (ThreadPoolTaskExecutor) asyncExecutorConfig.getAsyncExecutor();
//自己创建一个线程
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//输出线程名称
System.out.println("************"+Thread.currentThread().getName());
}
});
//将创建的线程放入线程池中
asyncExecutor.submit(thread);
//打印线程名称
long time2 = System.currentTimeMillis();
System.out.println("用时:"+(time2-time1));
}
自己写个springboot的demo项目, 自己创建一个线程池可以试试
还没有评论,来说两句吧...