2.1 Spring boot/cloud 執行緒池
阿新 • • 發佈:2018-11-26
Step 1:ExecutePool配置,開啟@EnableAsync支援非同步任務
package com.springboot.begin.threadPool; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; @Configuration @EnableAsync public class ExecutorPoolConfig { private int corePoolSize = 10; private int maxPoolSize = 50; private int queueSize = 10; private int keepAlive = 60; @Bean public Executor testExecutorPool() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueSize); executor.setKeepAliveSeconds(keepAlive); executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy()); executor.setThreadNamePrefix("TestExecutorPool-"); executor.initialize(); return executor; } }
Step 2:執行執行緒,宣告一個非同步任務
package com.springboot.begin.threadPool; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Slf4j @Component public class ThreadPoolUser { @Async("testExecutorPool") public void test(){ String info = "test---" + Thread.currentThread().getName(); log.info(info); } }
Step 3:測試 (介面呼叫)
package com.springboot.begin; import com.springboot.begin.threadPool.ThreadPoolUser; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; @RestController @Slf4j @RequestMapping(value = "/test") public class TestController { @Autowired private ThreadPoolUser threadPoolUser; @RequestMapping(value = "/threadpool/test" , method=RequestMethod.GET) public String threadPoolTest() { threadPoolUser.test(); return "ok"; } }