一、首先创建自定义async配置类,主要是为了在里面定义异步执行的线程池和自定义错误处理方法
@EnableAsync
@Configuration
public class AsyncExecutorConfig implements AsyncConfigurer {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(3);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(60);
executor.initialize();
return executor;
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new AsyncUncaughtExceptionHandler() {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
System.out.println("class#method: " + method.getDeclaringClass().getName() + "#" + method.getName());
System.out.println("type : " + ex.getClass().getName());
System.out.println("exception : " + ex.getMessage());
ex.printStackTrace();
}
};
}
}
二、在需要使用的地方使用@Async注解
@Component
public class MessageUtils {
@Autowired
private IUserService iUserService;
@Autowired
private IMessageService iMessageService;
//异步发送消息
//baseMsgId对应消息模板的id,params消息模板对应的参数,from发送人id,to接受人username
@Async
public void sendMsg(String baseMsgCode,String params,Integer from,String to){
//...
}
}
需要注意的:四个注解配置文件里面@EnableAsync @Configuration 使用的地方@Component @Async