Spring Boot如何异步运行方法呢?

戚薇 SpringBoot 发布时间:2023-06-09 22:27:11 阅读数:1097 1
下文笔者讲述SpringBoot异步运行的方法及示例分享,如下所示

异步运行方法的实现思路

在Springboot中,让方法异步,可采用以下方法
   只需使用@EnableAsync 和 @Async两个注解
       即可让方法异步运行
   @EnableAsync:
	  加载Springboot启动类上
   @Async:
      加载异步的方法上
例:异步方法的示例
package com.java265.aysncdemo.service;

public interface AsyncService {
    void asyncMethod(String arg);
}

package com.java265.aysncdemo.service.ipml;

import com.java265.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

    @Async
    @Override
    public void asyncMethod(String arg) {
        System.out.println("arg:" + arg);
        System.out.println("=====" + Thread.currentThread().getName() + "=========");
    }
}


@EnableAsync
//在启动类或者配置类加上 @EnableAsync 注解

package com.java265.aysncdemo;

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

@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(AysncDemoApplication.class, args);
    }
}



//测试代码

package com.java265.aysncdemo;

import com.java265.aysncdemo.service.AsyncService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AysncDemoApplicationTests {

    @Autowired
    AsyncService asyncService;

    @Test
    public void testAsync() {
        System.out.println("=====" + Thread.currentThread().getName() + "=========");
        asyncService.asyncMethod("Async");
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaFramework/SpringBoot/202306/6762.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者