SpringBoot-注解:@Async 使用

不同类中使用@Async

线程配置初始化类-ThreadPoolConfig

package com.zzdy.recharge.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.ThreadPoolExecutor;

/**

* 线程池配置

*/

@Configuration
@EnableAsync(proxyTargetClass = true)

public class ThreadPoolConfig {

private final int core = Runtime.getRuntime().availableProcessors() + 1;

/**

*

* @return

*/
@Bean(name = "rechargeMorenTaskExecutor")

public ThreadPoolTaskExecutor threadPoolTaskExecutor() {

ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

// 设置核心线程数

executor.setCorePoolSize(core);

// 设置最大线程数

executor.setMaxPoolSize(core * 2);

// 设置队列容量

executor.setQueueCapacity(128);

// 空闲时间

executor.setKeepAliveSeconds(300);

// 设置线程名称前缀

executor.setThreadNamePrefix("recharge-moren-thread-");

executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

// 执行初始化
executor.initialize();

return executor;

}

}

调用线程类

@Slf4j

@Service

public class DataAnalysisService{

@Async("rechargeMorenTaskExecutor")

public ReturnData dataAnalysisService(String body){

System.out.println(Thread.currentThread());

}

}

同一个类中调用需要先获取代理对象,也就是手动获取对象

复制代码
@Service
@EnableAsync
public class DemoService {
    public void add(){
        DemoService bean = SpringUtil.getBean(DemoService.class);
        System.out.println("开始o");
        bean.sendToKafka();
        System.out.println("结束o");
    }
    @Async
    public void sendToKafka() {
        try {
            Thread.sleep(10000);
            System.out.println(" 醒了!!! ");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

总结

1、在需要用到的@Async注解的类上加上@EnableAsync,或者直接加在springboot启动类上

2、异步处理方法(也就是加了@Async注解的方法)只能返回的是void或者Future类型

3、同一个类中调用异步方法需要先获取代理类,因为@Async注解是基于Spring AOP (面向切面编程)的,而AOP的实现是基于动态代理模式实现的。有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器。。。。。。这点很重要,也是经常遇到的

相关推荐
ZeroToOneDev1 小时前
Java(泛型和JUnit)
java·开发语言·笔记
许野平1 小时前
Rust:构造函数 new() 如何进行错误处理?
开发语言·后端·rust
mCell2 小时前
Go 并发定时任务避坑指南:从 Sleep 到 Context 的 8 种写法全解析
后端·性能优化·go
迪尔~2 小时前
Apache POI中通过WorkBook写入图片后出现导出PDF文件时在不同页重复写入该图片问题,如何在通过sheet获取绘图对象清除该图片
java·pdf·excel
现在,此刻3 小时前
leetcode 11. 盛最多水的容器 -java
java·算法·leetcode
快乐就是哈哈哈3 小时前
Spring Cloud Alibaba 教程:Nacos 配置中心 + Feign 服务调用一网打尽
后端
DKPT3 小时前
Java设计模式之开闭原则介绍与说明
java·设计模式·开闭原则
hyy27952276844 小时前
企业级WEB应用服务器TOMCAT
java·前端·tomcat
布朗克1684 小时前
Spring Boot项目通过Feign调用三方接口的详细教程
java·spring boot·feign