java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Springboot异步任务线程池

Springboot实现异步任务线程池代码实例

作者:gblfy

这篇文章主要介绍了Springboot实现异步任务线程池代码实例,异步任务线程池是一种用于处理异步任务的机制,它可以提高程序的并发性能和响应速度,通过将任务提交给线程池,线程池会自动管理线程的创建和销毁,从而避免了频繁创建和销毁线程的开销,需要的朋友可以参考下

异步任务线程池

异步任务线程池是一种用于处理异步任务的机制,它可以提高程序的并发性能和响应速度。

通过将任务提交给线程池,线程池会自动管理线程的创建和销毁,从而避免了频繁创建和销毁线程的开销。

同时,线程池还可以控制并发线程的数量,避免资源过度占用。

异步任务线程池是多线程编程中常用的一种技术,它可以应用于各种场景,如网络请求、数据库操作、文件处理等。

1. 启动类添加@EnableAsync注解

package com.gblfy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class JavaEscapeApplication {

    public static void main(String[] args) {
        SpringApplication.run(JavaEscapeApplication.class, args);
    }

}

2. 异步方法添加@Async注解

package com.gblfy.async_task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Slf4j
@Service
public class AsyncService {

    @Async
    public void asyncProcess01() throws Exception {
        log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName());
        Thread.sleep(2000);
        log.info("AsyncService Start to asyncProcess01 ->{}", Thread.currentThread().getName());
    }

    @Async
    public Future<String> asyncProcess02() throws Exception {
        log.info("AsyncService Start to asyncProcess02->{}", Thread.currentThread().getName());
        Thread.sleep(2000);
        log.info("AsyncService Done to asyncProcess02->{}", Thread.currentThread().getName());
        return new AsyncResult<>("imooc");
    }

    @Async
    public void asyncProcess03()  {
        log.info("AsyncService Start to asyncProcess03->{}", Thread.currentThread().getName());
        throw new RuntimeException("throw exception asyncProcess03");
    }
}

3. 自定义线程池以及线程池异常策略

package com.gblfy.async_task;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 自定义异步任务线程池
 */
@Slf4j
@Configuration
public class AsyncTaskConfig implements AsyncConfigurer {
    @Override
    public Executor getAsyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("cmiip-");
        executor.setCorePoolSize(15);
        executor.setMaxPoolSize(20);
        executor.setKeepAliveSeconds(5);
        executor.setQueueCapacity(100);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());

        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                //                报警邮件,发短信等等
                log.error("async task some Error: {} ,{} , {}", ex.getMessage(),
                        method.getDeclaringClass().getName() + "." + method.getName(),
                        Arrays.toString(params));
            }
        };
    }
}

测试

package com.gblfy.async_task;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@Slf4j
@SpringBootTest
class AsyncServiceTest {


    @Autowired
    private AsyncService asyncService;

    @Test
     void contextLoads() throws Exception {
//        asyncService.asyncProcess01();
        Future<String> future= asyncService.asyncProcess02();
        log.info("Async Process02 return :->{}", future.get(1, TimeUnit.SECONDS));
    }

    @Test
    void contextLoads2() throws Exception {
         asyncService.asyncProcess03();
         Thread.sleep(3000);
    }
}

到此这篇关于Springboot实现异步任务线程池代码实例的文章就介绍到这了,更多相关Springboot异步任务线程池内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文