美文网首页
Springboot 异步线程示例

Springboot 异步线程示例

作者: SlowGO | 来源:发表于2019-01-07 16:56 被阅读0次

    定义线程池

    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
    

    相关文章

      网友评论

          本文标题:Springboot 异步线程示例

          本文链接:https://www.haomeiwen.com/subject/zqzurqtx.html