美文网首页
自定义注解实现一个可配置线程池

自定义注解实现一个可配置线程池

作者: ZhangDHing | 来源:发表于2019-07-25 16:09 被阅读0次

前言

 项目需要多线程执行一些Task,为了方便各个服务的使用。特意封装了一个公共工具类,下面直接撸代码:

PoolConfig(线程池核心配置参数):

/**
 * <h1>线程池核心配置(<b style="color:#CD0000">基本线程池数量、最大线程池数量、队列初始容量、线程连接保持活动秒数(默认60s)</b>)</h1>
 * 
 * <blockquote><code>
 * <table border="1px" style="border-color:gray;" width="100%"><tbody>
 * <tr><th style="color:green;text-align:left;">
 * 属性名称
 * </th><th style="color:green;text-align:left;">
 * 属性含义
 * </th></tr>
 * <tr><td>
 * queueCapacity
 * </td><td>
 * 基本线程池数量
 * </td></tr>
 * <tr><td>
 * count
 * </td><td>
 * 最大线程池数量
 * </td></tr>
 * <tr><td>
 * maxCount
 * </td><td>
 * 队列初始容量
 * </td></tr>
 * <tr><td>
 * aliveSec
 * </td><td>
 * 线程连接保持活动秒数(默认60s)
 * </td></tr>
 * </tbody></table>
 * </code></blockquote>

 */
public class PoolConfig {

    private int queueCapacity = 200;

    private int count = 0;

    private int maxCount = 0;

    private int aliveSec;

    public int getQueueCapacity() {
        return queueCapacity;
    }   

    public void setQueueCapacity(int queueCapacity) {
        this.queueCapacity = queueCapacity;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public void setMaxCount(int maxCount) {
        this.maxCount = maxCount;
    }

    public void setAliveSec(int aliveSec) {
        this.aliveSec = aliveSec;
    }

    public int getCount() {
        return count;
    }

    public int getMaxCount() {
        return maxCount;
    }

    public int getAliveSec() {
        return aliveSec;
    }
}

image.gif

ThreadPoolConfig(线程池配置 yml/poperties配置项以thread开头):

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * <h1>线程池配置(<b style="color:#CD0000">线程池核心配置、各个业务处理的任务数量</b>)</h1>
 * 
 * <blockquote><code>
 * <table border="1px" style="border-color:gray;" width="100%"><tbody>
 * <tr><th style="color:green;text-align:left;">
 * 属性名称
 * </th><th style="color:green;text-align:left;">
 * 属性含义
 * </th></tr>
 * <tr><td>
 * pool
 * </td><td>
 * 线程池核心配置
 * 【{@link PoolConfig}】
 * </td></tr>
 * <tr><td>
 * count
 * </td><td>
 * 线程池各个业务任务初始的任务数
 * </td></tr>
 * </tbody></table>
 * </code></blockquote>

 */
@Component
@ConfigurationProperties(prefix="thread")
public class ThreadPoolConfig {

    private PoolConfig pool = new PoolConfig();

    Map<String, Integer> count = new HashMap<>();

    public PoolConfig getPool() {
        return pool;
    }

    public void setPool(PoolConfig pool) {
        this.pool = pool;
    }

    public Map<String, Integer> getCount() {
        return count;
    }

}

image.gif

定义Task注解,方便使用

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ExcutorTask {

    /**
     * The value may indicate a suggestion for a logical ExcutorTask  name,
     * to be turned into a Spring bean in case of an autodetected ExcutorTask  .
     * @return the suggested ExcutorTask  name, if any
     */
    String value() default "";

}
image.gif

通过反射获取使用Task注解的任务集合:

public class Beans {

    private static final char PREFIX = '.';

    public static ConcurrentMap<String, String> scanBeanClassNames(){
        ConcurrentMap<String, String> beanClassNames = new ConcurrentHashMap<>();
        ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);  
        provider.addIncludeFilter(new AnnotationTypeFilter(ExcutorTask.class));
        for(Package pkg : Package.getPackages()){
            String basePackage = pkg.getName();
            Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);  
            for (BeanDefinition component : components) {
                String beanClassName = component.getBeanClassName();
                try {
                    Class<?> clazz = Class.forName(component.getBeanClassName());
                    boolean isAnnotationPresent = clazz.isAnnotationPresent(ZimaTask.class);
                    if(isAnnotationPresent){
                        ZimaTask task = clazz.getAnnotation(ExcutorTask.class);
                        String aliasName = task.value();
                        if(aliasName != null && !"".equals(aliasName)){
                            beanClassNames.put(aliasName, component.getBeanClassName());
                        }
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                beanClassNames.put(beanClassName.substring(beanClassName.lastIndexOf(PREFIX) + 1), component.getBeanClassName());
            }
        }
        return beanClassNames;
    }

}
image.gif

线程执行类TaskPool

@Component
public class TaskPool {

    public ThreadPoolTaskExecutor poolTaskExecutor;

    @Autowired 
    private ThreadPoolConfig threadPoolConfig;

    @Autowired  
    private ApplicationContext context;

    private final Integer MAX_POOL_SIZE = 2000;

    private PoolConfig poolCfg;

    private Map<String, Integer> tasksCount;

    private ConcurrentMap<String, String> beanClassNames;

    @PostConstruct
    public void init() {

        beanClassNames = Beans.scanBeanClassNames();

        poolTaskExecutor = new ThreadPoolTaskExecutor();

        poolCfg = threadPoolConfig.getPool();

        tasksCount = threadPoolConfig.getCount();

        int corePoolSize = poolCfg.getCount(), 
                maxPoolSize = poolCfg.getMaxCount(), 
                queueCapacity = poolCfg.getQueueCapacity(), 
                minPoolSize = 0, maxCount = (corePoolSize << 1);

        for(String taskName : tasksCount.keySet()){
            minPoolSize += tasksCount.get(taskName);
        }

        if(corePoolSize > 0){
            if(corePoolSize <= minPoolSize){
                corePoolSize = minPoolSize;
            }
        }else{
            corePoolSize = minPoolSize;
        }

        if(queueCapacity > 0){
            poolTaskExecutor.setQueueCapacity(queueCapacity);
        }

        if(corePoolSize > 0){
            if(MAX_POOL_SIZE < corePoolSize){
                corePoolSize = MAX_POOL_SIZE;
            }
            poolTaskExecutor.setCorePoolSize(corePoolSize);
        }

        if(maxPoolSize > 0){
            if(maxPoolSize <= maxCount){
                maxPoolSize = maxCount;
            }
            if(MAX_POOL_SIZE < maxPoolSize){
                maxPoolSize = MAX_POOL_SIZE;
            }
            poolTaskExecutor.setMaxPoolSize(maxPoolSize);
        }

        if(poolCfg.getAliveSec() > 0){
            poolTaskExecutor.setKeepAliveSeconds(poolCfg.getAliveSec());
        }

        poolTaskExecutor.initialize();
    }

    public void execute(Class<?>... clazz){
        int i = 0, len = tasksCount.size();
        for(; i < len; i++){
            Integer taskCount = tasksCount.get(i);
            for(int t = 0; t < taskCount; t++){
                try{
                    Object taskObj = context.getBean(clazz[i]);
                    if(taskObj != null){
                        poolTaskExecutor.execute((Runnable) taskObj);
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    public void execute(String... args){
        int i = 0, len = tasksCount.size();
        for(; i < len; i++){
            Integer taskCount = tasksCount.get(i);
            for(int t = 0; t < taskCount; t++){
                try{
                    Object taskObj = null;
                    if(context.containsBean(args[i])){
                        taskObj = context.getBean(args[i]);
                    }else{
                        if(beanClassNames.containsKey(args[i].toLowerCase())){
                            Class<?> clazz = Class.forName(beanClassNames.get(args[i].toLowerCase()));
                            taskObj = context.getBean(clazz);
                        }
                    }
                    if(taskObj != null){
                        poolTaskExecutor.execute((Runnable) taskObj);
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

    public void execute(){
        for(String taskName : tasksCount.keySet()){
            Integer taskCount = tasksCount.get(taskName);
            for(int t = 0; t < taskCount; t++){
                try{
                    Object taskObj = null;
                    if(context.containsBean(taskName)){
                        taskObj = context.getBean(taskName);
                    }else{
                        if(beanClassNames.containsKey(taskName)){
                            Class<?> clazz = Class.forName(beanClassNames.get(taskName));
                            taskObj = context.getBean(clazz);
                        }
                    }
                    if(taskObj != null){
                        poolTaskExecutor.execute((Runnable) taskObj);
                    }
                }catch(Exception ex){
                    ex.printStackTrace();
                }
            }
        }
    }

}
image.gif

如何使用?(做事就要做全套 _

1.因为使用的springboot项目,需要在application.properties 或者 application.yml 添加

#配置执行的task线程数
thread.count.NeedExcutorTask=4
#最大存活时间
thread.pool.aliveSec=300000
#其他配置同理
image.gif

2.将我们写的线程配置进行装载到我们的项目中

@Configuration
public class TaskManager {

    @Resource
    private TaskPool taskPool;

    @PostConstruct
    public void executor(){
        taskPool.execute();
    }
}

image.gif

3.具体使用

@ExcutorTask
public class NeedExcutorTask implements Runnable{
    @Override
    public void run() {
        Thread.sleep(1000L);
        log.info("====== 任务执行 =====")
    }
}
image.gif

以上就是创建一个可扩展的线程池相关的配置(望指教~~~)。


相关文章

  • 使用@Async注解创建多线程,自定义线程池

    说明 使用@Async注解创建多线程非常的方便,还可以通过配置,实现线程池。比直接使用线程池简单太多。而且在使用上...

  • @EnabelAsync

    @EnabelAsync注解的使用。如不指定自定义异步线程池直接使用@EnableAsync即可使用,若自定义线程...

  • java 实现自定义线程池

    java 实现自定义线程池 定义线程池接口 线程池接口的默认实现 示例摘抄于《Java并发变成的艺术》4.4.3线...

  • spring定时任务

    一 配置 多线程存在阻塞问题,所以需要配置线程池 详见:spring定时任务详解(@Scheduled注解) 二 ...

  • 自定义注解实现一个可配置线程池

    前言 PoolConfig(线程池核心配置参数): ThreadPoolConfig(线程池配置 yml/pope...

  • Spring Boot 配置异步Async方法

    注解启动类 添加线程池配置 标注异步方法-不带返回值 标注异步方法-不带返回值 线程池的调用过程 核心线程池未满时...

  • 在Swagger中显示枚举值

    一、实现代码 1.1 自定义注解 1.2 Swagger配置拦截自定义注解 1.3 枚举类 重点:重写toStri...

  • Springboot 异步线程示例

    定义线程池 @EnableAsync 注解开开启异步。 实现 AsyncConfigurer,重写 getAsyn...

  • java线程池源码分析

    从线程池使用进行实现分析一.自定义线程池1.自定义线程池2.构造完成之后状态3.关键参数介绍二.执行任务1.exe...

  • 并发--共享模型之工具

    线程池 1.1 自定义线程池 先自定义任务队列 自定义线程池 测试: 定义拒绝策略接口: 1.2 ThreadPo...

网友评论

      本文标题:自定义注解实现一个可配置线程池

      本文链接:https://www.haomeiwen.com/subject/rnihrctx.html