Springcloud 自定义线程池

如何解决 JDK 线程池不超过最大线程数下快速消费任务

ThreadConfig.java

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Configuration
public class ThreadConfig {

    /**
     * 邮件服务
     * @return
     */
    @Bean("sendMailExecutorService")
    public ExecutorService sendMailExecutorService() {
        return new ThreadPoolExecutor(2, 2,
                60L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
    }

    /**
     * 心跳服务
     * @return
     */
    @Bean("heartbeatExecutorService")
    public ExecutorService heartbeatExecutorService() {
        return new ThreadPoolExecutor(1, 1,
                60L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>());
    }
    
	/**
     * 消费队列线程
     * @return
     */
    @Bean("consumerQueueThreadPool")
    public ExecutorService buildConsumerQueueThreadPool(){
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("consumer-queue-thread-%d").build();

        ExecutorService pool = new ThreadPoolExecutor(5, 5, 0L, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<Runnable>(5),namedThreadFactory,new ThreadPoolExecutor.AbortPolicy());

        return pool ;
    }
}

ThreadService.java

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

@Service
public class ThreadService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Qualifier("sendMailExecutorService")
    @Autowired
    private ExecutorService sendMailExecutorService;

    @Qualifier("heartbeatExecutorService")
    @Autowired
    private ExecutorService heartbeatExecutorService;

	@Resource(name = "consumerQueueThreadPool")
    private ExecutorService consumerQueueThreadPool;

    public void heartbeatService() {
        heartbeatExecutorService.submit(() -> {

            // TODO 负责心跳有关的工作
            logger.info("Execute heartbeatService asynchronously, thread name = {}", Thread.currentThread().getName());

        });
    }

    public Future<Boolean> sendMailService() {
        return sendMailExecutorService.submit(() -> {

            logger.info("Execute sendMailService asynchronously, thread name = {}", Thread.currentThread().getName());

            // 休息1秒,模拟邮件发送过程
            TimeUnit.SECONDS.sleep(1);
            return true;
        });
    }

	public void execute() {
        //消费队列
        for (int i = 0; i < 5; i++) {
            consumerQueueThreadPool.execute(new ConsumerQueueThread());
        }
    }
}

ThreadController.java

import com.ckjava.test.service.ThreadService;
import com.ckjava.xutils.Constants;
import com.ckjava.xutils.http.HttpResponse;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api
@RestController
@RequestMapping(value = "/api/asyncThread", produces = "application/json;charset=utf-8")
public class ThreadController {

    @Autowired
    private ThreadService threadService;

    /**
     * 请求,立即返回,但是不是具体的执行结果,具体的任务在线程池中慢慢的执行
     */
    @GetMapping("/heartbeat")
    public HttpResponse<String> asyncData() {
        threadService.heartbeatService();
        return HttpResponse.getReturn(null, HTTPCODE.code_200, STATUS.SUCCESS);
    }

    /**
     * 请求,执行完毕后再返回具体的结果,具体的任务在线程池中执行
     */
    @GetMapping("/sendMail")
    public HttpResponse<Boolean> asyncGetData() throws Exception {
        return HttpResponse.getReturn(threadService.sendMailService().get(), HTTPCODE.code_200, STATUS.SUCCESS);
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值