后台用异步线程调用的场景与常用方式
一.异步执行的场景:
完成业务后,发短信、发邮件、微信公众号等消息推送提示的功能,可以采用异步执行。
在导入数量量过大等情况下,可以使用异步导入的方式,提高导入时间等。
...等等
二.实现的方式:
1.springboot中,进行线程池配置,然后用@Async标识异步执行方法即可,如下:(需要注意的@EnableAsync和@Async不能在同一个类中 | 实现AsyncConfigurer的类只能有一个 | 这种方式的异步没有返回值,不适用与需要等待执行完成的场景。)
@Configuration @EnableAsync public class ExecutorConfig implements AsyncConfigurer { private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class); @Value("${async.executor.thread.core_pool_size}") private int corePoolSize; @Value("${async.executor.thread.max_pool_size}") private int maxPoolSize; @Value("${async.executor.thread.queue_capacity}") private int queueCapacity; @Value("${async.executor.thread.keep_alive_seconds}") private int keepAliveSeconds; @Value("${async.executor.thread.name.prefix}") private String namePrefix; @Bean(name = "asyncExecutor") public Executor asyncServiceExecutor() { logger.info("开启SpringBoot的线程池!"); ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // 设置核心线程数 executor.setCorePoolSize(corePoolSize); // 设置最大线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程 executor.setMaxPoolSize(maxPoolSize); // 设置缓冲队列大小 executor.setQueueCapacity(queueCapacity); // 设置线程的最大空闲时间,超过了核心线程数之外的线程,在空闲时间到达之后会被销毁 executor.setKeepAliveSeconds(keepAliveSeconds); // 设置线程名字的前缀,设置好了之后可以方便我们定位处理任务所在的线程池 executor.setThreadNamePrefix(namePrefix); // 设置拒绝策略:当线程池达到最大线程数时,如何处理新任务 // CALLER_RUNS:在添加到线程池失败时会由主线程自己来执行这个任务, // 当线程池没有处理能力的时候,该策略会直接在execute方法的调用线程中运行被拒绝的任务;如果执行程序已被关闭,则会丢弃该任务 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); // 线程池初始化 executor.initialize(); return executor; } @Override public Executor getAsyncExecutor() { return asyncServiceExecutor(); } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return (ex, method, params) -> logger.error(String.format("执行异步任务'%s'", method), ex); } }
public class useAsync { @Async(name = "asyncExecutor") public void asyncMethod(){ // 异步执行的业务代码 } }
2.需要返回值的异步线程池调用线程方式:
public void sum() throws ExecutionException, InterruptedException { ExecutorService executorService = Executors.newFixedThreadPool(4); List<Future<Integer>> futureList = new ArrayList<>(); for (int i=0;i<600;i++){ Future<Integer> futureSum = executorService.submit(new SumCall(Integer.valueOf(i))); futureList.add(futureSum); } // 关闭线程池 executorService .shutdown(); // 获取所有并发任务的运行结果,若需要等待并发任务执行完成的结果,在做其他业务,这里使用while循环配合一个完成标识flag就可以了。 for (Future<Integer> future : futureList){ System.out.println(future.get()); } } class SumCall implements Callable<Integer> { private int plus; public SumCall(int plus) { this.plus= plus; } @Override public Integer call() throws Exception { return 1+plus; } }
参考链接: https://blog.csdn.net/lemon_TT/article/details/122905103
参考链接:https://blog.csdn.net/ClaireCheney/article/details/107109340
标签:
异步与多线程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现