商品入库异步任务实现

之前做异步的时候通常都是用消息队列来做,今天使用spring的异步任务

首先异步任务需要定义线程池,spring异步提供了默认线程池,但是线程池通常都是自己定义,这样更能符合业务需求。

将自定义线程池注入到sprin中,并设置异步任务异常捕获处理器

package com.imooc.ecommerce.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
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.lang.reflect.Method;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created By 丛梓祺 on 2021/11/9
 * Write this code and change the world
 * 自定义异步任务线程池 异步任务异常捕获处理器
 */
@Slf4j
@EnableAsync  //开启spring 异步任务支持
@Configuration
public class AsyncPoolConfig implements AsyncConfigurer {
    
    /**
     * 将自定义线程池注入到spring容器中
     *
     * @return
     */
    @Bean
    @Override
    public Executor getAsyncExecutor() {
        //spring提供的自定义线程池
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(10);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(20);
        executor.setKeepAliveSeconds(60);
        //给这个线程池里的线程起一个名字,这个很重要
        executor.setThreadNamePrefix("czq-async-");
        //等待所有任务结果后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //线程池的等待时间
        executor.setAwaitTerminationSecond
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值