springboot单类集中定义线程池

简介: 该内容是关于Spring中异步任务的配置和使用步骤。首先,在启动类添加`@EnableAsync`注解开启异步支持。然后,自定义线程池类`EventThreadPool`,设置核心和最大线程数、存活时间等参数。接着,将线程池bean注入到Spring中,如`@Bean("RewardThreadPool")`。最后,在需要异步执行的方法上使用`@Async`注解,例如在一个定时任务类中,使用`@Scheduled(cron = "...")`和`@Async`结合实现异步定时任务。

 1、在启动类上加注解  @EnableAsync

2、定义线程池的类

package com.javabase.Thread;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.*;
public class EventThreadPool extends ThreadPoolExecutor {
    /**
     * 定义线程工厂名称
     */
    private static ThreadFactory HANDLEREMINDWAY_FACTORY = new ThreadFactoryBuilder()
            .setNameFormat("EventThreadPool-%d").build();
    public EventThreadPool() {
        super(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 30,
                20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000), HANDLEREMINDWAY_FACTORY,new CallerRunsPolicy());
    }
//    public ThreadPoolExecutor getThreadPoolExecutor() {
//        return new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors(), Runtime.getRuntime().availableProcessors() * 30,
//            20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
//    }
    public EventThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
        /**
         *
         * (ArrayBlockingQueue读写只有一个锁(效率更高),LinkedBlockingQueue读写锁分离)
         * LinkedBlockingQueue即无界队列.
         * 将ArrayBlockingQueue即无界队列的大小设置为1000.
         * 使用无界队列
         * 将LinkedBlockingQueue即无界队列的大小设置为500.
         * 将导致在所有 corePoolSize线程都忙的情况下将新任务加入队列,
         * 这样,创建的线程就不会超过 corePoolSize, 而且当排队的任务超过500时,将拒绝执行
         */
        super(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(1000), Executors
                .defaultThreadFactory());
    }
}

image.gif

3、注入工厂到spring中

package com.javabase.Thread;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
    @Bean("RewardThreadPool")
    public ThreadPoolExecutor rewardThreadPool() {
        return new EventThreadPool();
    }
    @Bean("reportThreadPool")
    public ThreadPoolExecutor reportThreadPool() {
        return new EventThreadPool();
    }
    @Bean("roomReservationThreadPool")
    public ThreadPoolExecutor roomReservationThreadPool() {
        return new EventThreadPool();
    }
}

image.gif

4、在自己的方法中使用

package com.javabase.Thread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
 * 构建执行定时任务
 * TODO
 */
@Component
@EnableScheduling
public class ScheduledTask3 {
    private Logger logger = LoggerFactory.getLogger(ScheduledTask3.class);
 
    private int fixedDelayCount = 1;
    private int fixedRateCount = 1;
    private int initialDelayCount = 1;
    private int cronCount = 1;
 
  /*  @Scheduled(fixedDelay = 5000)        //fixedDelay = 5000表示当前方法执行完毕5000ms后,Spring scheduling会再次调用该方法
    public void testFixDelay() {
        logger.info("===fixedDelay: 第{}次执行方法", fixedDelayCount++);
    }
 
    @Scheduled(fixedRate = 5000)        //fixedRate = 5000表示当前方法开始执行5000ms后,Spring scheduling会再次调用该方法
    public void testFixedRate() {
        logger.info("===fixedRate: 第{}次执行方法", fixedRateCount++);
    }
 
    @Scheduled(initialDelay = 1000, fixedRate = 5000)   //initialDelay = 1000表示延迟1000ms执行第一次任务
    public void testInitialDelay() {
        logger.info("===initialDelay: 第{}次执行方法", initialDelayCount++);
    }*/
 
    /*@Scheduled(cron = "0 0/1 * * * ?")  //cron接受cron表达式,根据cron表达式确定定时规则
    public void testconfigureTasks() {
        logger.info("===initialDelay: 第{}次执行方法", cronCount++);
    }*/
    @Async("RewardThreadPool")
    @Scheduled(cron = "0/1 * * * * ?")
    public void testtaskExecutor() {
        logger.info("ScheduledTask3定时任务开始 :{} " + "\r\n线程 : {}", LocalDateTime.now().toLocalTime(), Thread.currentThread().getName());
        logger.info("===initialDelay: 第{}次执行方法", cronCount++);
    }
}

image.gif


目录
相关文章
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——定义返回的统一 json 结构
本课主要讲解Spring Boot中的全局异常处理方法。在项目开发中,各层操作难免会遇到各种异常,若逐一处理将导致代码耦合度高、维护困难。因此,需将异常处理从业务逻辑中分离,实现统一管理与友好反馈。本文通过定义一个简化的JsonResult类(含状态码code和消息msg),结合全局异常拦截器,展示如何封装并返回标准化的JSON响应,从而提升代码质量和用户体验。
398 0
|
Java 数据库 开发者
详细介绍SpringBoot启动流程及配置类解析原理
通过对 Spring Boot 启动流程及配置类解析原理的深入分析,我们可以看到 Spring Boot 在启动时的灵活性和可扩展性。理解这些机制不仅有助于开发者更好地使用 Spring Boot 进行应用开发,还能够在面对问题时,迅速定位和解决问题。希望本文能为您在 Spring Boot 开发过程中提供有效的指导和帮助。
2502 12
|
前端开发 Java 数据格式
SpringBoot中定义Bean的几种方式
本文介绍了Spring Boot中定义Bean的多种方式,包括使用@Component、@Bean、@Configuration、@Import等注解及Java配置类。每种方式适用于不同的场景,帮助开发者高效管理和组织应用组件。
772 0
|
并行计算 Java 数据处理
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
SpringBoot高级并发实践:自定义线程池与@Async异步调用深度解析
1219 0
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
1006 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
Java API Spring
springBoot:注解&封装类&异常类&登录实现类 (八)
本文介绍了Spring Boot项目中的一些关键代码片段,包括使用`@PathVariable`绑定路径参数、创建封装类Result和异常处理类GlobalException、定义常量接口Constants、自定义异常ServiceException以及实现用户登录功能。通过这些代码,展示了如何构建RESTful API,处理请求参数,统一返回结果格式,以及全局异常处理等核心功能。
269 1
|
Java
SpringBoot线程问题
SpringBoot线程问题
277 0
|
JSON 缓存 前端开发
SpringBoot的 ResponseEntity类讲解(具体讲解返回给前端的一些事情)
本文讲解了SpringBoot中的`ResponseEntity`类,展示了如何使用它来自定义HTTP响应,包括状态码、响应头和响应体,以及如何将图片从MinIO读取并返回给前端。
1456 3
|
Java Spring 容器
Springboot3.2.1搞定了类Service和bean注解同名同类型问题修复
这篇文章讨论了在Spring Boot 3.2.1版本中,同名同类型的bean和@Service注解类之间冲突的问题得到了解决,之前版本中同名bean会相互覆盖,但不会在启动时报错,而在配置文件中设置`spring.main.allow-bean-definition-overriding=true`可以解决这个问题。
1024 0
Springboot3.2.1搞定了类Service和bean注解同名同类型问题修复
|
算法 NoSQL Java
Springboot3新特性:GraalVM Native Image Support和虚拟线程(从入门到精通)
这篇文章介绍了Spring Boot 3中GraalVM Native Image Support的新特性,提供了将Spring Boot Web项目转换为可执行文件的步骤,并探讨了虚拟线程在Spring Boot中的使用,包括如何配置和启动虚拟线程支持。
1478 9
Springboot3新特性:GraalVM Native Image Support和虚拟线程(从入门到精通)

热门文章

最新文章