springboot 通过任务执行器TaskExecutor来实现多线程和并发编程

1.前言

Springt通过任务执行器(TaskExecutor)来实现多线程和并发编程。使用ThreadPoolTaskExecutor可实现一个基于线程池的TaskExecutor。而实际开发中任务一般是非阻碍的,即异步的,所以我们要在配置类中通过@EnableAsync 开启对异步任务的支持,并通过实际执行Bean的方法中使用@Async注解来声明其是一个异步任务。

2.基于springboot实现

1.配置类

配置类实现AsyncConfigurer接口,并重写getAsyncExecutor方法,并返回一个ThreadPoolTaskExecutor,这样我们就获得一个基于线程池TaskExecutor。


import java.util.concurrent.Executor;

import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author caiqingheng
 * @date 2020年8月7日 
 * 
 */

@Configurable
@EnableAsync
public class CustomMultiThreadingConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor(){
        
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(5);
        taskExecutor.setMaxPoolSize(10);
        taskExecutor.setQueueCapacity(25);
        taskExecutor.initialize();
        return taskExecutor;
    }
    
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return AsyncConfigurer.super.getAsyncUncaughtExceptionHandler();
    }
}

2.控制层

/**
 * xcwlkj.com Inc.
 * Copyright (c) 2015-2030 All Rights Reserved.
 */
package com.xcwlkj.fivedollars.controller.manager;

import javax.annotation.Resource;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xcwlkj.fivedollars.service.ArticleService;
import com.xcwlkj.util.wrapper.WrapMapper;
import com.xcwlkj.util.wrapper.Wrapper;


@RestController
@RequestMapping(value = "", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class ArticleController extends BaseController {

    @Resource
    private ArticleService articleService;

	
    @PostMapping(value = "/manager/article/queryArticleList")
    public Wrapper<QueryArticleListRespModel> queryArticleList(@RequestBody QueryArticleListReqModel reqModel) {

        
        //多线程异步调用测试
        for (int i = 0; i < 10; i++) {
            articleService.executeAsyncTask1(i);
            articleService.executeAsyncTask2(i);
        }
            	
    }

}

 

3.接口


import org.springframework.stereotype.Service;

import com.xcwlkj.fivedollars.model.dto.article.AddArticleDTO;
import com.xcwlkj.fivedollars.model.dto.article.DeleteArticleDTO;
import com.xcwlkj.fivedollars.model.dto.article.QueryArticleDetailDTO;
import com.xcwlkj.fivedollars.model.dto.article.QueryArticleListDTO;
import com.xcwlkj.fivedollars.model.dto.article.UpdateArticleDTO;
import com.xcwlkj.fivedollars.model.vo.article.QueryArticleDetailVO;
import com.xcwlkj.fivedollars.model.vo.article.QueryArticleListVO;

@Service
public interface ArticleService  {


    void executeAsyncTask1(int i);

    void executeAsyncTask2(int i);
}

4.实现类

import java.util.Date;
import javax.annotation.Resource;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service("articleService")
public class ArticleServiceImpl  implements ArticleService  {
	
	@Async
    @Override
    public void executeAsyncTask1(int i) {
        
	    System.out.println("executeAsyncTask1======>{}"+i);
    }
	
	@Async
    @Override
    public void executeAsyncTask2(int i) {
	    
	    System.out.println("executeAsyncTask2======>{}"+i);
    }
}

5.访问

http://localhost:8662/manager/article/queryArticleList

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在Spring Boot中,可以使用@Scheduled注解来实现定时任务,可以结合@Async注解来实现多线程异步。 首先,需要在启动类上添加@EnableAsync注解,开启异步支持。然后在要执行异步任务的方法上添加@Async注解。 接下来,可以使用Java中的Executor框架来创建线程池,用于执行异步任务。可以在应用程序中创建一个线程池,并使用@Async注解将任务提交给线程池执行。 下面是一个示例代码: ```java @Configuration @EnableAsync public class AsyncConfig { @Bean(name = "taskExecutor") public Executor taskExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(10); executor.setMaxPoolSize(20); executor.setQueueCapacity(30); executor.setThreadNamePrefix("MyAsyncThread-"); executor.initialize(); return executor; } } @Service public class MyService { @Async("taskExecutor") @Scheduled(cron = "0 0 12 * * ?") //每天中午12点执行 public void myAsyncTask() { //异步任务内容 } } ``` 在上面的示例中,我们创建了一个名为“taskExecutor”的线程池,并将其注入到MyService中的myAsyncTask方法中。该方法使用@Async注解来指示它应该在异步线程中执行。@Scheduled注解指定了任务执行的时间。 需要注意的是,@Async注解只有在调用该方法的类通过Spring容器进行管理时才会生效。如果通过new关键字手动创建对象,@Async注解将不起作用。 希望这可以帮助你完成Spring Boot定时任务整合多线程异步的实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值