Spring bootマルチスレッドサポート
5685 ワード
プロジェクトでは、実行時間が長いタスクがよく発生します.この時は、マルチスレッドを使って処理したいと考えています.この需要はよく使われていますので、私達のspring大人は直接にフレームレベルから実現してくれます.
実例コード:webインターフェース非同期
MuttiThreadAplication
実例コード:webインターフェース非同期
MuttiThreadAplication
@SpringBootApplication
@EnableAsync // ,
public class MutiThreadApplication {
//
@Bean
public Executor getExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(25);
executor.setAwaitTerminationSeconds(20000);
return executor;
}
public static void main(String[] args) {
SpringApplication.run(MutiThreadApplication.class, args);
}
}
TestControllerpackage com.liao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.liao.service.TestService;
@RestController
public class TestController {
@Autowired
private TestService testService;
@RequestMapping("/test")
public String test() {
System.out.println("main:start");
testService.test();
System.out.println("main:end");
return "end";
}
}
TestServicepackage com.liao.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class TestService {
@Async // ,spirng
public void test() {
System.out.println(Thread.currentThread().getName()+":start");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+":end");
}
}
実行結果web要求は直ちに結果に戻ります.システムログは以下の通りです.main:start
main:end
getExecutor-1:start
getExecutor-1:end