Spring

您所在的位置:网站首页 ocschool学校 Spring

Spring

2023-10-04 11:51| 来源: 网络整理| 查看: 265

1、首先使用@Async 需要在Spring启动类上添加注解@EnableAsyn或者在你们线程池配置类添加@EnableAsyn

一下两种选择一种即可

@SpringBootApplication @EnableAsync public class SpringBootApplicationStart { public static void main(String[] args) { SpringApplication.run(SpringBootApplicationStart.class); } }

 

@EnableAsync @Configuration public class ThreadPoolConfig { @Bean("simpleThreadPool") public ThreadPoolTaskExecutor simpleThreadPool(){ ThreadPoolTaskExecutor simpleThreadPool = new ThreadPoolTaskExecutor(); simpleThreadPool.setCorePoolSize(5); simpleThreadPool.setMaxPoolSize(10); simpleThreadPool.setQueueCapacity(25); simpleThreadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); simpleThreadPool.initialize(); return simpleThreadPool; } }

注意如果自己配置了线程池那么在使用的时候需要保持一致

例如:@Async("simpleThreadPool")

2、在使用@Async的时候切记不要在一个类里面调用@Async声明的方法,会产生代理绕过问题。

@Async public void asyncProcess() throws InterruptedException { Thread.sleep(2000); }

 

3、注意写法

@Autowired private AsyncTaskService asyncTaskService; public String asyncMethod(String name,int age) { OnelogStats.trace("msg_async", "进入service"); try { // 初学者可能会有这种错误,AsyncTaskService没有注入到Spring导致Async不起作用,注释不规范 //new AsyncTaskService().asyncProcess(); asyncTaskService.asyncProcess(); } catch (InterruptedException e) { return "async error"; } return "I am " + name + ", I am " + age + " years old."; }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3