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

相关推荐
代码丰12 小时前
大模型 + RAG 幻觉治理方案总结
后端
小村儿12 小时前
(译文)重温:Karpathy 的 4 条 CLAUDE.md 规则将 Claude 错误率从 41% 降至 11%——历经 30 个代码库后,我又加了 8 条
前端·后端·ai编程
user696007375661712 小时前
3个前端性能优化技巧,我用后页面加载快了80%
后端
源码集结号12 小时前
基于 Spring Boot + JPA + MySQL的上门家政系统代码示例
java·前端·后端
该用户已不存在12 小时前
别再把 Claude 当聊天框,Claude Code CLI 安装与上下文管理指北(Part 1)
后端·ai编程·claude
蝎子莱莱爱打怪13 小时前
无废话!源自官网的Codex 命令速查手册!
人工智能·后端·agent
盖世英雄酱5813613 小时前
6000条数据执行时间9s(二)
数据库·后端
是梦终空13 小时前
计算机源码273—基于SpringBoot+Vue3停车场管理系统带支沙箱支付(源代码+数据库)
数据库·spring boot·vue·mybatis·停车场管理系统·沙箱支付·毕设设计
Filwaod13 小时前
Java面试:AIGC场景下的技术深度拷问-谢飞机篇
spring boot·缓存·微服务·消息队列·aigc·java面试·ai技术
程序员老邢13 小时前
【技术底稿 32】Nginx 经典大坑复盘:本机公网域名自环代理,导致接口返回首页 / 404 实战排障
java·运维·nginx·前后端分离·技术底稿·后端部署