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

相关推荐
毕业设计-小慧3 分钟前
计算机毕业设计springboot游戏数据管理系统 基于SpringBoot的电竞赛事数据管理平台 基于SpringBoot的在线游戏运营数据分析系统
spring boot·游戏·课程设计
平生不喜凡桃李4 分钟前
浅谈 Linux 中 namespace 相关系统调用
java·linux·服务器
zb2006412010 分钟前
CVE-2024-38819:Spring 框架路径遍历 PoC 漏洞复现
java·后端·spring
uzong18 分钟前
AI Agent 是什么,如何理解它,未来挑战和思考
人工智能·后端·架构
2401_8955213420 分钟前
spring-ai 下载不了依赖spring-ai-openai-spring-boot-starter
java·人工智能·spring
追逐时光者31 分钟前
DotNetGuide突破了10K + Star,一份全面且免费的C#/.NET/.NET Core学习、工作、面试指南知识库!
后端·.net
何仙鸟1 小时前
GarmageSet下载和处理
java·开发语言
wefly20171 小时前
免安装!m3u8live.cn在线 M3U8 播放器,小白也能快速上手
java·开发语言·python·json·php·m3u8·m3u8在线转换
yuweiade1 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
ywf12151 小时前
springboot设置多环境配置文件
java·spring boot·后端