springboot的异步编程

springboot的异步编程
异步编程的含义:当前任务不受其他任务影响。
第一步:线程池配置类上使用@EnableAsync,@Bean注解定义线程池名称。配置线程池的大小、最大线程数、队列容量、活跃时间、线程名称前缀、拒绝策略。


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

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义创建Async使用线程池
 */
@Configuration
@EnableAsync
public class TaskExecutePool implements AsyncConfigurer {
    
    

    @Bean(name = "taskPool")
    public Executor taskPool() {
    
    
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(8);
        //最大线程数
        executor.setMaxPoolSize(999);
        //队列容量
        executor.setQueueCapacity(999);
        //活跃时间
        executor.setKeepAliveSeconds(999);
        //线程名字前缀
        executor.setThreadNamePrefix("abc-");
        // 拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

}

第二步:使用@Async(“线程池名称”)实现异步编程

@Service
@Slf4j
public class DefectServiceImpl implements DetailService {
    
    
	@Override
    @Async("taskPool")
    public void generateInspectReport( String token) {
    
    }
}    

猜你喜欢

转载自blog.csdn.net/m0_49382941/article/details/129590126