当在你在应用中处理正常流程时,有时一些储存数据或者一些其他操作(不影响应用流程),这时就可以将其作为一个任务放入异步线程池中进行异步调用,提高应用响应速度。
下面就是主要代码:
创建线程池对象
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
@Configuration
public class ThreadPoolConfig {
@Bean(value = "threadPoolInstance")
public ExecutorService createThreadPoolInstance() {
//通过guava类库的ThreadFactoryBuilder来实现线程工厂类并设置线程名称
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("thread-pool-%d").build();
ExecutorService threadPool = new ThreadPoolExecutor(10, 16, 60L, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(500), threadFactory, new ThreadPoolExecutor.AbortPolicy());
return threadPool;
}
}
异步调用方法使用示例
public void invokeMethod(User user){
executorService.submit(new PushDataTask(user));
}
class PushDataTask implements Callable<Boolean> {
public User user;
public PushDataTask(User user) {
this.user = user;
}
@Override
public Boolean call() throws Exception {
logger.info("异步执行开始==================================>>>>>>>>>>>");
try {
//执行异步方法
ThirdMethodService.push(user,1l);
} catch (Exception e) {
logger.info("异步执行异常==================================>>>>>>>>>>>");
} finally {
logger.info("异步执行结束==================================>>>>>>>>>>>");
}
return true;
}
}
以上就是一个大概的异步方法调用。如果需要将方法异步执行,直接使用即可。
日拱一卒,得寸进尺。