因业务需要,经常会遇到主线程中包含其他关联业务,然关联业务的执行结果对主线程的返回结果没有直接影响或无影响。此时,能让主线程更顺畅的执行,并给客户带来好的客户体验,我们一般会将该关联业务做异步处理或类似的处理(如:消息队列),本文记录自己在项目中使用异步服务的相关经历,以备后期查询使用!
一、Springboot 使用异步任务
1、SpringBootApplication启动类添加@EnableAsync注解;
2、@Async使用
(1)类或者方法中使用@Async注解,类上标有该注解表示类中方法都是异步方法,方法上标有该注解表示方法是异步方法;
(2)@Async(“threadPool”),threadPool为自定义线程池,这样可以保证主线程中调用多个异步任务时能更高效的执行。
3、实例、分析
开启异步服务
@SpringBootApplication
@EnableApolloConfig
@EnableAsync
@ComponentScan(basePackages = {"com.zts"})
public class UserMgmtApplication {
public static void main(String[] args) {
SpringApplication.run(UserMgmtApplication.class, args);
}
}
定义异步类或方法:如果异步方法需要返回值,可以用Future<Object>接收
@Service
public class TestServiceImpl implements TestCRMService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
@Async("testAsync") // 自定义执行线程池
public void sendMessage() throws Exception {
/**
* 业务实现
*/
}
@Override
@Async("testAsync") // 自定义执行线程池
public void sendMail() throws Exception {
/**
* 业务实现
*/
}
}
调用异步方法
@Autowired
TestService testService;
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@RequestMapping(value = "/test", method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(notes = "test()", httpMethod = "GET", value = "测试调用多个异步任务")
public Map<String,Object> runTaskByKettle( ) throws Exception{
Map<String,Object> result = new HashMap<>();
try {
testService.sendMessage();
} catch (Exception e) {
e.printStackTrace();
logger.error("sendMessage任务出现异常");
}
try {
testService.sendMail();
} catch (Exception e) {
e.printStackTrace();
logger.error("sendMail任务出现异常");
}
return result;
}
自定义线程池
@Configuration
@EnableAsync
public class ExecutorConfig {
/** Set the ThreadPoolExecutor's core pool size. */
private int corePoolSize = 10;
/** Set the ThreadPoolExecutor's maximum pool size. */
private int maxPoolSize = 50;
/** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
private int queueCapacity = 10;
@Bean
public Executor testAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix("MgmtExecutor-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
至此,Springboot 调用多个异步任务使用实例完成。
@Async注解 分析
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {
String value() default "";
}
通过查看@Async源码可以看出来,@Target 的值是类和方法,所有异步注解可以作用在方法体上面,也可以作用在类上面。
以上是项目使用,可正常使用,因此验证忽略!
二、Spring boot异步任务@Async失效问题
总结:1、启动类是否开启异步服务;
2、在定义异步方法的同一个类中,调用带有@Async
注解方法,该方法则无法异步执行;
3、注解的方法必须是public方法,不能是static;
4、没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器管理。