首页 > 其他分享 >springboot-异步使用

springboot-异步使用

时间:2024-06-07 15:24:49浏览次数:13  
标签:异步 springboot org 使用 springframework 线程 executor import public

  • 创建配置类,开启异步和创建线程


package com.chulx.demo1.config;

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

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class MyAsyncConfig {
/**
* 自定义线程池
*/
@Bean("taskExecutor")
public Executor taskExecutor() {
// 返回可用处理器的Java虚拟机的数量 12
int i = Runtime.getRuntime().availableProcessors();
System.out.println("系统最大线程数 :" + i);
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
// 核心线程池大小
executor.setCorePoolSize(16);
// 最大线程数
executor.setMaxPoolSize(20);
// 配置队列容量,默认值为Integer.MAX_VALUE
executor.setQueueCapacity(99999);
// 活跃时间
executor.setKeepAliveSeconds(60);
// 线程名字前缀
executor.setThreadNamePrefix("asyncServiceExecutor -");
// 设置此执行程序应该在关闭时阻止的最大秒数,以便在容器的其余部分继续关闭之前等待剩余的任务完成他们的执行
executor.setAwaitTerminationSeconds(60);
// 等待所有的任务结束后再关闭线程池
executor.setWaitForTasksToCompleteOnShutdown(true);
return executor;
}

}
 
  • 创建异步服务
package com.chulx.demo1.asyncService;

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

@Service
public class MyAsyncService {
    @Async("taskExecutor")
    public void executeAsyncTask() throws InterruptedException {
        Thread.currentThread().sleep(5000);
        System.out.println("执行异步任务:" + Thread.currentThread().getName());
    }
}
  •     同步服务调用异步服务
package com.chulx.demo1.service.impl;

import com.chulx.demo1.asyncService.MyAsyncService;
import com.chulx.demo1.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AsyncImplService implements AsyncService {

    @Autowired
    private MyAsyncService myAsyncService;

    @Override
    public void doSomething() throws InterruptedException {
        System.out.println("this is sync service");
        myAsyncService.executeAsyncTask();
    }
}
  •   控制器调用
@RestController
@RequestMapping("async")
@RequiredArgsConstructor
public class MyAsyncController {

    private  final AsyncService asyncService;
    @RequestMapping("test")
    public String test() throws InterruptedException {
        System.out.println("test");
        asyncService.doSomething();
        System.out.println("test2");
        return "test";
    }
}

 

效果:

       

 

 

 

 

 

    

标签:异步,springboot,org,使用,springframework,线程,executor,import,public
From: https://www.cnblogs.com/chulx/p/18237249

相关文章