Java spring 使用线程池以及@Async 注解用法

一 springboot 注解方法 使用线程池

1.首先启动类上增加@EnableAsync注解

package cc.mrbird;

import cc.mrbird.common.config.NniuhaoProperies;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.time.LocalDate;
import java.time.LocalTime;

@SpringBootApplication
@EnableTransactionManagement
@MapperScan("cc.mrbird.*.dao")
@EnableConfigurationProperties({NniuhaoProperies.class})// 开启配置属性支持
@EnableCaching
@EnableAsync
public class Application /*extends SpringBootServletInitializer*/ {
    private static Logger log = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        log.info("NIUHAO started up successfully at {} {}", LocalDate.now(), LocalTime.now());
    }

}

2.编写自定义线程池

package cn.digirun.bizos.gateway.core.properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 功能描述: 配置自定义的线程池
 *
 * @auther: 钮豪
 * @date: 2018/11/1 17:58
 */

@Configuration//配置类把//普通pojo实例化到spring容器中
@EnableAsync//异步
public class ExecutorConfig {

    private static final Logger logger = LoggerFactory.getLogger(ExecutorConfig.class);

    @Bean
    public Executor getAsyncExecutor() {
        logger.info("start getAsyncExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(20);
        //配置最大线程数
        executor.setMaxPoolSize(50);
        //配置队列大小
        executor.setQueueCapacity(999);
        //活跃时间
        executor.setKeepAliveSeconds(60 * 15);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("-async-getAsyncExecutor-");
        // setRejectedExecutionHandler:当pool已经达到max size的时候,如何处理新任务
        // CallerRunsPolicy:不在新线程中执行任务,而是有调用者所在的线程来执行
        /*
        (1) 默认的ThreadPoolExecutor.AbortPolicy   处理程序遭到拒绝将抛出运行时RejectedExecutionException;
        (2) ThreadPoolExecutor.CallerRunsPolicy 线程调用运行该任务的 execute 本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度
        (3) ThreadPoolExecutor.DiscardPolicy  不能执行的任务将被删除;
        (4) ThreadPoolExecutor.DiscardOldestPolicy  如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)。*/
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

    @Bean
    public Executor getAsyncExecutor2() {
        logger.info("start getAsyncExecutor");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(20);
        //配置最大线程数
        executor.setMaxPoolSize(50);
        //配置队列大小
        executor.setQueueCapacity(9999);
        //活跃时间
        executor.setKeepAliveSeconds(60 * 15);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("-async-");
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

3.接口使用

package cn.digirun.bizos.gateway.service;

import cn.digirun.bizos.gateway.core.token.TokenBean;
import cn.digirun.bizos.gateway.model.TokenRet;
import org.springframework.scheduling.annotation.Async;

import java.util.concurrent.Future;

/**
 * @Auther: Administrator
 * @Date: 2019/4/20 10:54
 * @Description:
 */
public interface TokenGatewayService {
    @Async(value = "getAsyncExecutor")
    Future<TokenRet>  create(TokenBean bean)throws Exception;
    @Async(value = "getAsyncExecutor2")
    Future<TokenRet> get(String token)throws Exception;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章