【SpringBoot】8.SpringBoot中的异步任务

SpringBoot 中的异步任务主要是指在 SpringBoot 中使用异步线程完成处理任务。

在 SpringBoot 中使用异步线程非常简单,只需要两个注解就可以搞定。一个是 @EnableAsync (用于开启异步注解),另一个是 @Async (一般加在方法上,表示该方法异步执行)。

1、使用自带的线程池实现异步任务

第一步

在启动类上加上注解 @EnableAsync ,如下所示

在这里插入图片描述

第二步

写接口,并将接口的实现方法,用注解 @Async 标识。

  • controller层
package com.yuhuofei.controller;

import com.yuhuofei.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @ClassName AsyncController
 * @Author yuhuofei
 * @Date 2022/8/22 21:51
 * @Version 1.0
 */
@RestController
@RequestMapping("/async")
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/getAsyncHello")
    public String getAsyncHello(){
        return asyncService.getHello();
    }
}

  • service层接口
package com.yuhuofei.service;

/**
 * @Description
 * @ClassName AsyncService
 * @Author yuhuofei
 * @Date 2022/8/22 21:55
 * @Version 1.0
 */
public interface AsyncService {

    String getHello();
}

  • service层接口实现类
package com.yuhuofei.service;

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

/**
 * @Description
 * @ClassName AsyncServiceImpl
 * @Author yuhuofei
 * @Date 2022/8/22 21:55
 * @Version 1.0
 */
@Service
public class AsyncServiceImpl implements AsyncService {

    @Override
    @Async
    public String getHello() {
        return "hello,测试一下";
    }
}

至此完成异步任务的简单实现。

2、使用自定义的线程池实现异步任务

第一步

自定义一个线程池,如下所示

package com.yuhuofei.config;

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

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author yuhuofei
 * @version 1.0
 * @description 自定义异步线程池
 * @date 2022/8/22 21:55
 */
@Configuration
@EnableAsync
public class AsyncExecutorConfig {
    private static final int CORE_POOL_SIZE = 10;

    private static final int MAX_POOL_SIZE = 20;

    private static final int QUEUE_CAPACITY = 2000;

    private static final String THREAD_NAME_PREFIX = "AsyncExecutor-self";

    private static final int KEEP_ALIVE_SECONDS = 60 * 10;

    @Bean("asyncExecutor")
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CORE_POOL_SIZE);
        executor.setMaxPoolSize(MAX_POOL_SIZE);
        executor.setQueueCapacity(QUEUE_CAPACITY);
        executor.setThreadNamePrefix(THREAD_NAME_PREFIX);
        executor.setAllowCoreThreadTimeOut(true);
        executor.setKeepAliveSeconds(KEEP_ALIVE_SECONDS);
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

第二步

使用自定义线程池,如下所示
在这里插入图片描述

package com.yuhuofei.service;

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

/**
 * @Description
 * @ClassName AsyncServiceImpl
 * @Author yuhuofei
 * @Date 2022/8/22 21:55
 * @Version 1.0
 */
@Service
public class AsyncServiceImpl implements AsyncService {

    @Override
    @Async("asyncExecutor")
    public String getHello() {
        return "hello,测试一下";
    }
}

由于自定义线程池时已经开启了异步注解,因此可以不用在启动类上加了,至此完成使用自定义线程池实现异步任务。

  • 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、付费专栏及课程。

余额充值