从零开始SpringCloud Alibaba实战(38)——SpringCloud线程池的使用

前言

项目中通常会实现异步调用的功能,如导出等。一般都是采用多线程技术,比如创建ThreadPoolTaskExecutor类。

在这里插入图片描述

线程池的创建


 
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
 
/**
 * 描述:自定义线程池的创建

 */
@Configuration
@EnableAsync
public class ThreadPoolExecutorConfig {
  @Bean
  public Executor threadPoolConfig() {
    ThreadPoolTaskExecutor  executor = new ThreadPoolTaskExecutor();
    //设置核心线程数
    executor.setCorePoolSize(5);
    //设置最大线程数
    executor.setMaxPoolSize(10);
    //设置队列容量
    executor.setQueueCapacity(20);
    // 设置线程活跃时间(秒)
    executor.setKeepAliveSeconds(60);
    //设置默认线程名称
    executor.setThreadNamePrefix("=线程池=");
    // 线程池对拒绝任务的处理策略:这里采用了CallerRunsPolicy策略,
    // 当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //等待所有任务结束后再关闭线程池
    executor.setWaitForTasksToCompleteOnShutdown(true);
    //进行初始化线程池
    executor.initialize();
    return executor;
  }

其中@EnableAsync注解用于开启多线程,可以放在入口启动类上(@SpringBootApplication注解的类)也可以放在java config配置类(ThreadPoolExecutorConfig )。

应用

直接在Spring容器管理的对象的方法上添加@Async注解显示调用即可生效,如下TestController中调用customerService服务,customerService中的threadPool方法添加了@Async注解:

CustomerService 接口


package com.demo.service;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class CustomerService {
    @Async
    public void threadPool() {
        LoggerFactory.getLogger(CustomerService.class).info("***" + ":Hello World!");
    }
 
}

TestController类



import com.huiyu.demo.service.CustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private CustomerService customerService;
    @RequestMapping("threadPool")
    public Object threadPool() {
        customerService.threadPool();
        return "threadPool";
    }
}

注意:@Async还有一个参数用于显示指定自定义创建的线程池,如@Async(“threadPoolConfig”)的threadPoolConfig对应的是ThreadPoolExecutorConfig类的方法名。如果上例中设置的线程池参数不满足业务需求,可以另外定义合适的线程池,调用时指明使用这个线程池,默认springboot会优先使用名称为’taskExecutor’的线程池,如果没有找到,才会使用其他类型为Executor或其子类的线程池。

有时候我们不止希望异步执行任务,还希望任务执行完成后会有一个返回值,在java中提供了Future泛型接口,用来接收任务执行结果,springboot也提供了此类支持,使用实现了ListenableFuture接口的类如AsyncResult来作为返回值的载体。比如上例中,我们希望返回一个类型为String类型的值,可以将返回值改造为:

@Async
public ListenableFuture<String> threadPoolReturn() {
    String res = "return  :Hello World!";
    LoggerFactory.getLogger(CustomerService.class).info(res);
    return new AsyncResult<>(res);
}

调用
// 阻塞调用
customerService.threadPoolReturn().get();
// 限时调用
customerService.threadPoolReturn().get(1, TimeUnit.SECONDS);

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值