springboot实现异步请求@Async

有时需要提交请求后可以立即返回,不需要等待业务方法执行完成才返回。

特别需要注意:@Async注解需要放在service实现方法上。

实现步骤如下:

一、在springboot启动类上添加注解@EnableAync

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

import com.idreamsky.ex.bpm.func.vo.Response;

@SpringBootApplication
@EnableAsync
public class MyProjectApplication {

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

二、添加异步配置类

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.concurrent.ThreadPoolTaskExecutor;
import org.springframework.util.StringUtils;


@Configuration
public class AsyncConfig implements AsyncConfigurer {

	private Logger logger = LoggerFactory.getLogger(AsyncConfig.class);
	
	@Bean
	@Override
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 根据自己机器配置
		executor.setCorePoolSize(8);
		executor.setMaxPoolSize(16);
		executor.setQueueCapacity(64);
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		executor.setThreadNamePrefix("SpringAsyncThread-");

		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SpringAsyncExceptionHandler();
	}

    // 异步调用异常处理
	class SpringAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
		
		@Override
		public void handleUncaughtException(Throwable throwable, Method method, Object... objects) {
			// 通过反射获取各个初始化方法名字
			String methodName = method.getName();
			logger.info("Async error. methodName = {}, errorInfo = {}", methodName, throwable.toString());
		}
		
	}
	
	
}

 三、在service实现方法上,加上@Async注解。

@Service
public class MyServiceImpl implements MyService {

    @Async
	@Override
	public void testAsync() {
        try {
			Thread.sleep(5000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值