使用Spring的@Async异步

系列文章目录



一、使用Spring的@Async异步

1.自定义异步线程池

在使用@Async注解时,调用方法和@Async标注方法不能在同一个类中,会造成异步失效。


/**
 * 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
 *
 * @EnableAsync
 * @Configuration public class TaskPoolConfig {
 * /**
 * 自定义线程池
 **/
//原文链接:https://blog.youkuaiyun.com/askuld/article/details/132053999

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;

/**
 * 线程池参数配置,多个线程池实现线程池隔离,@Async注解,默认使用系统自定义线程池,可在项目中设置多个线程池,在异步调用的时候,指明需要调用的线程池名称,比如:@Async("taskName")
 *
 * @EnableAsync
 * @Configuration
 *
 */
@Configuration
@EnableAsync
public class TaskPoolConfig {

    // 启动类要加注解

    @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;
    }
}
@Slf4j
@Service
public class AsyncServiceImpl {

    @Async("taskExecutor")
    public Object sendSms(String mobile, String content) {
        try {
            System.err.println("发送短信 -> " + mobile + " -> " + content + "");
            Thread.sleep(5000);
            System.err.println("发送成功 -> " + mobile + " -> " + content + "");
        } catch (Exception e) {
            log.error("发送短信异常 -> ", e);
        }
        return null;
    }
}    

    @Async("taskExecutor")
    public Future<String> sendSms(String mobile, String content) {
        try {
            System.err.println("发送短信 -> " + mobile + " -> " + content + "");
            Thread.sleep(5000);
            System.err.println("发送成功 -> " + mobile + " -> " + content + "");
        } catch (Exception e) {
            log.error("发送短信异常 -> ", e);
        }
        return  new AsyncResult("OK");
    }

二、其他参考

添加链接描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值