springboot異步處理請求 結合自定義線程池


package yinhu.yinhu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import yinhu.yinhu.yh.vo.AsyncTest;

@Controller
@EnableAsync
public class AsyncController {
    @Autowired
    private AsyncTest asyncTest;
    @ResponseBody
    @GetMapping
    @RequestMapping(value="/async")
    public String test() {
        asyncTest.mywait();
        System.out.println("wait");
        return "ok";
    }

}
package yinhu.yinhu.yh.vo;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTest {
    @Async("taskExecutor")//自己配置的自定義線程池的名字(也就是帶bean的方法名);也可以不要,不要的話就只能用框架自帶的線程池
    public void mywait() {
        System.out.println("------------------oh no");
        // TODO Auto-generated method stub
        try {
            Thread.sleep(1000*10);
            System.out.println("線程名字"+Thread.currentThread().getName());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("------------------oh yes");
    }
}
package yinhu.yinhu.yh.config;

import java.util.concurrent.Executor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
public class MyAsyncTaskThreadPool {
    private int poolsize=10;
    private int maxpoolsize=200;
    private int queueCapacity=10;
    
    @Bean
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(poolsize);
        threadPoolTaskExecutor.setMaxPoolSize(maxpoolsize);
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        threadPoolTaskExecutor.setThreadNamePrefix("線程前綴名字");
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }
    
}

springboot異步處理請求並響應的方式
controller加@EnableAsync注解
組件類(如)中的方法上方加@Async注解


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM