SpringBoot实现异步

Posted cppdy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot实现异步相关的知识,希望对你有一定的参考价值。

1、创建AsyncTest类

package com.cppdy.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class AsyncTest {
    
    @Async
    public void asyncOut() {
        System.out.println("异步方法id:"+Thread.currentThread().getId());
    }

}

2、在UserController中创建测试方法

@RequestMapping("async")
    public String async() {
        System.out.println("Main Thread Id:"+Thread.currentThread().getId());
        asyncTest.asyncOut();
        return "async";
    }

3、在Application类中开启异步(@EnableAsync)

package com.cppdy;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class Application {
    
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

}

 

以上是关于SpringBoot实现异步的主要内容,如果未能解决你的问题,请参考以下文章

springboot隔离@Async异步任务的线程池

Spring Boot | 事件监听器异步处理事件,实现代码解耦

Springboot-async

SpringBoot @Async实现异步调用

@Async异步注解与SpringBoot结合使用

springboot+async异步接口实现和调用