Be driven duck to write Java, framework will not use, this is purely my notes, big guys do not need to see ~ ~
Create a thread pool and customize the rejection policy
@Configuration public class TaskExecutorConfig { @Value("#{10}") private Integer corePoolSize; @Value("#{100}") private Integer maxPoolSize; @Value("#{200}") private Integer queueCapacity; @Value("#{10}") private Integer keepAliveSeconds; @Value("#{'taskExecutor'}") private String threadNamePrefix; @Bean public TaskExecutor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); // Set the number of core threads executor.setCorePoolSize(corePoolSize); SetMaxPoolSize (corePoolSize); / / set the queue capacity executor. SetQueueCapacity (queueCapacity); / / sets the thread active time (in seconds) executor. SetKeepAliveSeconds (keepAliveSeconds); / / set the default thread name executor. SetThreadNamePrefix (threadNamePrefix); / / set to refuse strategy executor. SetRejectedExecutionHandler (new CustomAbortPolicy ()); / / waiting for the end of all the tasks and then close the thread pool executor. SetWaitForTasksToCompleteOnShutdown (true); Executor.initialize (); // Set the waiting time of tasks in the thread pool, and force the destruction of executor.initialize() if the task has not been destroyed by this time; return executor; } } @Slf4j class CustomAbortPolicy implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { if (! Executor.isshutdown ()) {try {log.error("FULL-->> Thread pool is FULL, execute reject policy "); executor.getQueue().put(r); } catch (InterruptedException e) { log.error("interruptedException=" + e); }}}}Copy the code
Annotate @async (“taskExecutor”) on a Service class method that requires Async, and return a value of type Future<> if any.
@Async("taskExecutor") public Future<String> findTown(JSONObject jsonObject) throws IOException { if (jsonObject.containsKey("town") && ! StringUtils.isEmpty(jsonObject.get("town").toString().trim())) return new AsyncResult<>(jsonObject.get("town").toString()); return new AsyncResult<>(""); }Copy the code
If multiple return values are asynchronous, you can store all returned Future<> results in an array and then iterate through the array, fetching the resulting value from each Future<>
List<Future<String>> List = new ArrayList<>(); List<String> result = new ArrayList<>(); For (String address :addresses) list.add(findTownservice.findtown ((JSONObject)) jsonObject.get(address.trim()))); For (Future<String> r: list) result.add(r.set ());Copy the code
Remember to annotate @enableAsync on the startup class
@EnableAsync public class DataManagementApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(DataManagementApplication.class, args); }}Copy the code