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容器。。。。。。这点很重要,也是经常遇到的

相关推荐
朱昆鹏15 分钟前
开源 Claude Code + Codex + 面板 的未来vibecoding平台
前端·后端·github
REDcker17 分钟前
gRPC开发者快速入门
服务器·c++·后端·grpc
figo10tf17 分钟前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
zhangyi_viva21 分钟前
Spring Boot(七):Swagger 接口文档
java·spring boot·后端
橙露25 分钟前
Spring Boot 核心原理:自动配置机制与自定义 Starter 开发
java·数据库·spring boot
小程故事多_8026 分钟前
Agent Infra核心技术解析:Sandbox sandbox技术原理、选型逻辑与主流方案全景
java·开发语言·人工智能·aigc
冰暮流星26 分钟前
sql语言之分组语句group by
java·数据库·sql
望舒51329 分钟前
代码随想录day25,回溯算法part4
java·数据结构·算法·leetcode
黎雁·泠崖30 分钟前
【魔法森林冒险】3/14 Allen类(一):主角核心属性与初始化
java·开发语言
程序员敲代码吗31 分钟前
Spring Boot与Tomcat整合的内部机制与优化
spring boot·后端·tomcat