@Async顾名思义就是异步调用的意思,使用线程
在Spring boot中使用方便。
1.在启动类加入@EnableAsync注解
/**
* springboot启动器
* @author zsy
*/
@EnableAsync
@MapperScan(basePackages = "com.ismartgo.*.mapper")
@SpringBootApplication
public class CampApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(CampApplication.class);
}
public static void main(String[] args) {
SpringApplication.run(CampApplication.class, args);
}
@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return new EmbeddedServletContainerCustomizer() {
@Override
public void customize(ConfigurableEmbeddedServletContainer container) {
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/page/common/401.html");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/page/common/404.html");
container.addErrorPages(error401Page, error404Page);
}
};
}
}
2.定义一个线程池配置
package com.ismartgo.ep.common.config;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
public class ExecutorConfig {
@Bean
public Executor asyncServiceExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//配置核心线程数
executor.setCorePoolSize(5);
//配置最大线程数
executor.setMaxPoolSize(50);
//配置队列大小
executor.setQueueCapacity(999);
//配置线程池中的线程的名称前缀
executor.setThreadNamePrefix("async-service-");
// rejection-policy:当pool已经达到max size的时候,如何处理新任务
// CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
//执行初始化
executor.initialize();
return executor;
}
}
3.在方法加入相应注解即可使用异步调用方法
package com.ismartgo.ep.bridge.service;
import org.springframework.retry.annotation.Retryable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.retry.annotation.Backoff;
import org.springframework.stereotype.Service;
import com.ismartgo.ep.utils.HttpRequestUtil;
import net.sf.json.JSONObject;
@Service
public class CampCfgBridgeRetryService {
@Async("asyncServiceExecutor")
public void callback(JSONObject json , String requestUrl) throws Exception {
HttpRequestUtil.httpPostReturnStr(requestUrl, json);
}
}