1. 程式人生 > >Spring boot多執行緒支援

Spring boot多執行緒支援

專案中經常會遇到一些執行時間較長的任務,這個時候很容易就想到使用多執行緒來處理。由於這個需求太常用,因此我們的spring大佬就直接幫我們從框架層面實現。

例項程式碼:web介面非同步

MutiThreadApplication

@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); } }

TestController

package 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"; } }

TestService

package 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