欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringBoot实现线程池

程序员文章站 2022-04-06 22:24:11
现在由于系统越来越复杂,导致很多接口速度变慢,这时候就会想到可以利用线程池来处理一些耗时并不影响系统的操作。新建spring boot项目1. executorconfig.xml新建线程池配置文件。...

现在由于系统越来越复杂,导致很多接口速度变慢,这时候就会想到可以利用线程池来处理一些耗时并不影响系统的操作。

新建spring boot项目

1. executorconfig.xml

新建线程池配置文件。

@configuration
@enableasync
public class executorconfig {

    private static final logger logger = loggerfactory.getlogger(executorconfig.class);

    @value("${async.executor.thread.core_pool_size}")
    private int corepoolsize;
    @value("${async.executor.thread.max_pool_size}")
    private int maxpoolsize;
    @value("${async.executor.thread.queue_capacity}")
    private int queuecapacity;
    @value("${async.executor.thread.name.prefix}")
    private string nameprefix;

    @bean(name = "asyncserviceexecutor")
    public executor asyncserviceexecutor() {
        logger.info("start asyncserviceexecutor");
        threadpooltaskexecutor executor = new threadpooltaskexecutor();
        //配置核心线程数
        executor.setcorepoolsize(corepoolsize);
        //配置最大线程数
        executor.setmaxpoolsize(maxpoolsize);
        //配置队列大小
        executor.setqueuecapacity(queuecapacity);
        //配置线程池中的线程的名称前缀
        executor.setthreadnameprefix(nameprefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // caller_runs:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }
}

2. application.yml

@value配置在application.yml,可以参考配置

# 异步线程配置
async:
  executor:
    thread:
      # 配置核心线程数
      core_pool_size: 10
      # 配置最大线程数
      max_pool_size: 20
      # 配置队列大小
      queue_capacity: 99999
      # 配置线程池中的线程的名称前缀
      name:
        prefix: async-service-

3. asyncservice.java

创建一个 service 接口,是异步线程的接口,将方法写入其实现类即可

public interface asyncservice {

    /** 
      * 执行异步任务的方法,参数自己可以添加
      */
    void executeasync();
}

4. asyncserviceimpl.java

实现类,用来写业务逻辑

@service
public class asyncserviceimpl implements asyncservice {

    private static final logger logger = loggerfactory.getlogger(asyncserviceimpl.class);

    @override
    @async("asyncserviceexecutor")
    public void executeasync() {
        logger.info("start executeasync");

        system.out.println("异步线程执行开始了");
        system.out.println("可以将耗时的操作放到这里执行了");

        logger.info("end executeasync");
    }
}

++将 service 层的服务异步化,在executeasync()方法上增加注解@async("asyncserviceexecutor"),asyncserviceexecutor方法是前面executorconfig.java中的方法名,表明executeasync方法进入的线程池是asyncserviceexecutor方法创建的。++

5. asynccontroller.java

在控制器里面注入asyncservice,调用其中的方法即可

@autowired
private asyncservice asyncservice;

@getmapping("/async")
public void async(){
    asyncservice.executeasync();
}

6. 用postman进行测试

打印log入下

2021-06-16 22:15:47.655  info 10516 --- [async-service-5] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:15:47.655  info 10516 --- [async-service-5] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:15:47.770  info 10516 --- [async-service-1] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:15:47.770  info 10516 --- [async-service-1] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:15:47.816  info 10516 --- [async-service-2] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:15:47.816  info 10516 --- [async-service-2] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:15:48.833  info 10516 --- [async-service-3] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:15:48.834  info 10516 --- [async-service-3] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:15:48.986  info 10516 --- [async-service-4] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:15:48.987  info 10516 --- [async-service-4] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
至此简单的线程池已经实现了。

5. 将当前线程池的运行状况打印出来

5.1 visiablethreadpooltaskexecutor.java

public class visiablethreadpooltaskexecutor extends threadpooltaskexecutor {


    private static final logger logger = loggerfactory.getlogger(visiablethreadpooltaskexecutor.class);

    private void showthreadpoolinfo(string prefix) {
        threadpoolexecutor threadpoolexecutor = getthreadpoolexecutor();

        if (null == threadpoolexecutor) {
            return;
        }

        logger.info("{}, {},taskcount [{}], completedtaskcount [{}], activecount [{}], queuesize [{}]",
                this.getthreadnameprefix(),
                prefix,
                threadpoolexecutor.gettaskcount(),
                threadpoolexecutor.getcompletedtaskcount(),
                threadpoolexecutor.getactivecount(),
                threadpoolexecutor.getqueue().size());
    }

    @override
    public void execute(runnable task) {
        showthreadpoolinfo("1. do execute");
        super.execute(task);
    }

    @override
    public void execute(runnable task, long starttimeout) {
        showthreadpoolinfo("2. do execute");
        super.execute(task, starttimeout);
    }

    @override
    public future<?> submit(runnable task) {
        showthreadpoolinfo("1. do submit");
        return super.submit(task);
    }

    @override
    public <t> future<t> submit(callable<t> task) {
        showthreadpoolinfo("2. do submit");
        return super.submit(task);
    }

    @override
    public listenablefuture<?> submitlistenable(runnable task) {
        showthreadpoolinfo("1. do submitlistenable");
        return super.submitlistenable(task);
    }

    @override
    public <t> listenablefuture<t> submitlistenable(callable<t> task) {
        showthreadpoolinfo("2. do submitlistenable");
        return super.submitlistenable(task);
    }
}

5.2 修改asyncserviceexecutor.java

修改executorconfig.java的asyncserviceexecutor方法,将threadpooltaskexecutor executor = new threadpooltaskexecutor()改为threadpooltaskexecutor executor = new visiablethreadpooltaskexecutor()

@bean(name = "asyncserviceexecutor")
    public executor asyncserviceexecutor() {
        logger.info("start asyncserviceexecutor");
        //在这里修改
        threadpooltaskexecutor executor = new visiablethreadpooltaskexecutor();
        //配置核心线程数
        executor.setcorepoolsize(corepoolsize);
        //配置最大线程数
        executor.setmaxpoolsize(maxpoolsize);
        //配置队列大小
        executor.setqueuecapacity(queuecapacity);
        //配置线程池中的线程的名称前缀
        executor.setthreadnameprefix(nameprefix);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // caller_runs:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setrejectedexecutionhandler(new threadpoolexecutor.callerrunspolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

5.3 使用postman进行测试

2021-06-16 22:23:30.951  info 14088 --- [nio-8087-exec-2] u.d.e.e.i.visiablethreadpooltaskexecutor : async-service-, 2. do submit,taskcount [0], completedtaskcount [0], activecount [0], queuesize [0]
2021-06-16 22:23:30.952  info 14088 --- [async-service-1] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:23:30.953  info 14088 --- [async-service-1] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:23:31.351  info 14088 --- [nio-8087-exec-3] u.d.e.e.i.visiablethreadpooltaskexecutor : async-service-, 2. do submit,taskcount [1], completedtaskcount [1], activecount [0], queuesize [0]
2021-06-16 22:23:31.353  info 14088 --- [async-service-2] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:23:31.353  info 14088 --- [async-service-2] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:23:31.927  info 14088 --- [nio-8087-exec-5] u.d.e.e.i.visiablethreadpooltaskexecutor : async-service-, 2. do submit,taskcount [2], completedtaskcount [2], activecount [0], queuesize [0]
2021-06-16 22:23:31.929  info 14088 --- [async-service-3] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:23:31.930  info 14088 --- [async-service-3] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync
2021-06-16 22:23:32.496  info 14088 --- [nio-8087-exec-7] u.d.e.e.i.visiablethreadpooltaskexecutor : async-service-, 2. do submit,taskcount [3], completedtaskcount [3], activecount [0], queuesize [0]
2021-06-16 22:23:32.498  info 14088 --- [async-service-4] c.u.d.e.executor.impl.asyncserviceimpl   : start executeasync
异步线程执行开始了
可以将耗时的操作放到这里执行了
2021-06-16 22:23:32.499  info 14088 --- [async-service-4] c.u.d.e.executor.impl.asyncserviceimpl   : end executeasync

可以看到上面async-service-, 2. do submit,taskcount [3], completedtaskcount [3], activecount [0], queuesize [0]关于线程的信息都打印出来了。

 到此这篇关于springboot实现线程池的文章就介绍到这了,更多相关springboot 线程池内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!