[Spring Boot] Spring's asynchronous thread pool

Foreword

Thread pool, from the name, is that a saved thread "pool", everything has its truth, that the benefits of the thread pool where is it?

We want our computer to do some live, in fact, are using threads, it is to use a new Runnableinterface or create a new sub-class, inherited from the Threadclass, which will involve the creation and destruction of the thread object, these two operations will undoubtedly our system is consuming processor resources, then how to solve this problem? In fact, the thread pool is to solve this problem students.

Thread Pool provides a method of handling conflicts between system performance and a large amount of user requests, through multiple tasks 重用thread object that already exists, reduces the thread object creation and destruction overhead due to the time when the customer requests, the thread object 已经存在you can improve the response time of the request in order to improve the overall performance of the system services.

This blog is to summarize, how to use asynchronous thread pool in Spring, give you an example, to understand what the concept of asynchronous

Wang intern responsible for back office reporting analysis, his work is responsible for operating the back-end system, click the button to generate data reports, and does not need to see the report, due to the large amount of data, generate reports take a long time, and if generate reports and other work in a thread, Wang can not do other work, so other threads need to generate a report of this task to the computer, and this is reflected asynchronous.

Using asynchronous thread pool in Spring

spring provides AsyncConfigurerthe configuration interface for easy configuration of our own asynchronous thread pool.

New asynchronous configuration class

I used to create a new config package, and then some components are placed inside configuration class
Here Insert Picture Description

package com.example.wyh.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

/**
 * @author 阳光大男孩!!!
 */
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {
        //定义线程池
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //设置核心线程数
        threadPoolTaskExecutor.setCorePoolSize(10);
        //设置线程池最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(30);
        //设置线程队列最大线程数
        threadPoolTaskExecutor.setQueueCapacity(2000);
        //初始化线程池
        threadPoolTaskExecutor.initialize();

        return threadPoolTaskExecutor;
    }
}

In the above code, we used @Configurationto tell this spring is a configuration class, using annotations @EnableAsynclet spring turn available asynchronously. So that later if you want asynchronous task to put a method in another thread, only need to add a method @Asyncto comment.

Create a new service interface, and to achieve

package com.example.wyh.Service;

/**
 * @author 阳光大男孩!!!
 */
public interface AsyncService {

    /**
     * 测试使用异步线程池来执行工作
     */
    public void useAsyncThreadWork();
    
}

package com.example.wyh.Service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @author 阳光大男孩!!!
 */
@Service
public class AsyncServiceImp implements AsyncService{

    @Override
    @Async
    public void useAsyncThreadWork() {
        System.out.println(Thread.currentThread().getName());

    }
}

In the specific implementation of the interface, we print the name of the current thread, since by to see if the task is executed in the thread of a heart. And by @Servicetelling spring annotation Service This is a type of bean, so that we can make spring to manage our object through its own container, which is IOCa manifestation of characteristics.

Create a new Controller to access, test

/**
 * @author 阳光大男孩!!!
 */
@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;
    @GetMapping("/testAsync")
    public String testAsync()
    {
        System.out.println(Thread.currentThread().getName());
        asyncService.useAsyncThreadWork();
        return "testAsync方法执行成功...";
    }
}

It can be seen in the above code, we use @Autowirednotes to the automated assembly the Spring container just managed Serviceto achieve class object, which is the spring of DIcharacteristics embodied.

Because I drive a 8090 port, so my visit was to port 8090
Here Insert Picture Description
can see the printed names of the two threads, the first is the name of the execution of thread in the Controller, the second is the spring by our earlier configuration, and perform the appropriate task for us is that we extracted from the thread pool.
Here Insert Picture Description

to sum up

About this blog The basic method uses an asynchronous thread pool to perform tasks in the spring, it provides an example of using asynchronous thread pool in the project.

Published 247 original articles · won praise 109 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_43889841/article/details/104396275