zl程序教程

您现在的位置是:首页 >  后端

当前栏目

SpringBoot异步任务

2023-06-13 09:17:20 时间

SpringBoot异步任务

一、序言

在Java应用中,绝大多数情况下都是通过同步的方式来实现交互处理的;但是在处理与第三方系统交互的时候,容易造成响应迟缓的情况,之前大部分都是使用多线程来完成此类任务,其实,在Spring 3.x之后,就已经内置了@Async来完美解决这个问题。

二、测试步骤

1、创建AsyncService

这里先不加@Async注解,并让线程休眠3秒

package com.atguigu.springboot.service;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
    //告诉spring,这是一个异步方法
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中...");
    }
}

2、创建AsyncController

package com.atguigu.springboot.controller;

import com.atguigu.springboot.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @GetMapping("/hello")
    public String hello(){
        asyncService.hello();
        return "success";
    }
}

3、不使用异步注解时运行测试:

结果:访问http://localhost:8080/hello时,回卡一会才能出现success

4、使用异步注解

在AsyncService的方法里加上@Async注解 在启动类上面加上@EnableAsync注解开启注解功能

5、测试

使用了异步注解之后,页面直接显示success,控制台隔了3秒也正常输出处理数据中,说明确实是异步执行的