Springboot 异步线程示例(二)

原创
2020/07/24 17:26
阅读数 1.3K

一.定义线程池

import java.util.concurrent.Executor;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(30);
        executor.setQueueCapacity(1000);
        executor.initialize();
        
        return executor;
    }
}

@EnableAsync 注解开开启异步。

实现 AsyncConfigurer,重写 getAsyncExecutor(),设置线程池参数,返回 executor

定义异步service

接口

public interface AsyncService {
    public void asyncTest();
}

 

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

@Service
public class AsyncServiceImpl implements AsyncService {
    @Override
    @Async
    public void asyncTest() {
        System.out.println("【Thread】- " + Thread.currentThread().getName());
        //这里编写业务
    }
}

@Async 注解声明一个异步方法。

测试 controller

 

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {
    @Autowired
    AsyncService asyncService;
    
    @GetMapping("/test")
    public String test() {
        asyncService.asyncTest();
        return "test async";
    }
}

 

控制器的用法和同步方式一样,没有任何特殊的地方。

多次访问 /test,后台会输出不同的线程名称:

 

【Thread】- ThreadPoolTaskExecutor-1
【Thread】- ThreadPoolTaskExecutor-2
【Thread】- ThreadPoolTaskExecutor-3

参考文档:

https://www.jianshu.com/p/a98da5fac05e

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部