什么浏览器速度最快-迅雷7 1

异步调用
2023年4月5日发(作者:360国际版)

SpringBoot微服务异步调⽤@EnableAsync@Async

第⼀步:在Application启动类上⾯加上@EnableAsync注解

@SpringBootApplication

@EnableAsync

publicclassApplication{

publicstaticvoidmain(String[]args){

(,args);

}

}

第⼆步:定义[线程池]

@Configuration

@EnableAsync

@Component

publicclassAsyncConfig{

@Bean("asyncTaskExecutor")

publicTaskExecutorasyncTaskExecutor(){

ThreadPoolTaskExecutorexecutor=newThreadPoolTaskExecutor();

//设置核⼼线程数

ePoolSize(20);

//设置最⼤线程数

PoolSize(100);

//设置队列容量

ueCapacity(1000);

//设置线程活跃时间(秒)

pAliveSeconds(300);

//设置默认线程名称

eadNamePrefix("async-thread-pool-");

//设置拒绝策略

ectedExecutionHandler(olicy());

//等待所有任务结束后再关闭线程池

tForTasksToCompleteOnShutdown(true);

returnexecutor;

}

}

第三步:在异步⽅法上添加@Async

@Slf4j

@Service

@Component

publicclassAsyncServiceImplimplementsAsyncService{

@Async("asyncTaskExecutor")

@Override

publicvoidtestA(){

try{

n("开始testA");

(3000);

n("完成testA");

ThreadcurrentThread=tThread();

n("任务testA,当前线程:"+e());

}catch(Exceptione){

(sage(),e);

}

}

@Override

publicvoidtestB(){

try{

n("开始testB");

(3000);

n("完成testB");

ThreadcurrentThread=tThread();

n("任务testB,当前线程:"+e());

}catch(Exceptione){

(sage(),e);

}

}

}

第四步:测试

publicclassTest{

@Autowired

privateAsyncServiceasyncService;

@Test

publicvoidtestSyncTasks()throwsException{

longstart=currentTimeMillis();

();

longend=currentTimeMillis();

n("时间testA:"+(end-start));

longstart1=currentTimeMillis();

();

longend1=currentTimeMillis();

n("时间testB:"+(end1-start1));

}

}

输出结果:

时间testA:2

开始testB

开始testA

完成testA

完成testB

任务testA,当前线程:async-thread-pool-1

时间testB:3002

异步⽅法@Async注解失效情况:

(1)在@SpringBootApplication启动类没有添加注解@EnableAsync

(2)调⽤⽅法和异步⽅法写在同⼀个类,需要在不同的类才能有效。

(2)调⽤的是静态(static)⽅法

(3)调⽤(private)私有化⽅法

个别失效报错情况:

报错⼀:提⽰需要在@EnableAsync上设置proxyTargetClass=true来强制使⽤基于cglib的代理。注解上加上即可。

@EnableAsync(proxyTargetClass=true)

ConsiderinjectingthebeanasoneofitsinterfacesorforcingtheuseofCGLib-basedproxiesbysetting

proxyTargetClass=trueon@EnableAsyncand/or@EnableCaching

————————————————

更多推荐

异步调用