SpringBoot2 异步执行方法实例

SpringBoot2 异步执行方法实例

三丰 soft张三丰 java

异步处理就是按照不一样步的程序处理问题。异步处理与同步处理是对立的,而产生他们的是多线程或者多进程。异步处理的好处就是提升设备使用率,从而在宏观上提高程序运行效率,可是弊端就是容易出现冲突操做和数据脏读。同步则恰好相反,同步是一种下降设备使用率,在宏观上下降了程序的运行效率,并且不少系统或者是运行环境在处理同步的时候为了维持同步的有效性也会付出许多格外的系统资源开支,对性能影响至关大。可是同步保证了程序运行的正确性与数据的完整性。
SpringBoot2 异步执行方法实例数据库

SpringBoot 同步执行方法

学习 SpringBoot 异步执行方法 以前咱们先看一个同步执行的例子。多线程

首先是一个 Service 类:TestAsyncService.java,这里只是为了演示,就没有访问数据库和编写接口。app

@Service
public class TestAsyncService {

    public String getResult() {
        System.out.println("getResult() start...");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("getResult() end...");
        return "TestAsync";
    }
}

而后一个 Controller 类 :TestAsyncController , 调用 TestAsyncService 以下所示 。异步

@EnableAutoConfiguration
@RestController
public class TestAsyncController {

    @Autowired
    TestAsyncService testAsyncService;

    @RequestMapping("/testAsyncController")
    public String testAsyncController() {
        String result;
        System.out.println("testAsyncController() start...");

        result = testAsyncService.getResult();

        System.out.println("testAsyncController() end...");
        return "结果:" + result;
    }
}

从新启动工程,访问:http://localhost:8080/testAsyncControlleride

他会现有 3 秒 的卡顿,卡顿是由于 TestAsyncService。
而后出现结果:
SpringBoot2 异步执行方法实例
四条输出语句以下所示:
SpringBoot2 异步执行方法实例性能

SpringBoot 异步执行方法

SpringBoot 异步执行方法原理是建立了一个新的线程去运行 service 的方法,这会致使 controller 已经执行完成,而 service 还在运行,固然 controller 获取不到 service 的执行结果。使用到的注解是 @Async 。学习

第一步:修改启动类,须要添加@EnableAsync 这个注解开启异步调用。线程

// 启动类上加上@SpringBootApplication注解,当前包下或者子包下全部的类均可以扫到
@SpringBootApplication
// @EnableAsync 开启异步调用
@EnableAsync
public class SpringbootStudy01Application {

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

第二步:@Async 注解修饰 TestAsyncService,以下所示。3d

@Service
public class TestAsyncService {

    @Async
    public String getResult() {
        System.out.println("getResult() start...");
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("getResult() end...");
        return "TestAsync";
    }
}

TestAsyncController 不需修改,从新启动工程,访问 : http://localhost:8080/testAsyncController

运行截图以下所示:
SpringBoot2 异步执行方法实例
SpringBoot2 异步执行方法实例

显然,controller 已经执行完成,而 service 还在运行。

相关文章
相关标签/搜索