springboot任务之异步任务

先看同步的情况:

AysncService.java

package com.gong.spingbootes.service;

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

@Service
public class AysncService {
public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("处理数据中");;
    }
}

AysncController.java

package com.gong.spingbootes.controller;

import com.gong.spingbootes.service.AysncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AsyncController {

    @Autowired
    AysncService aysncService;

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

}

此时我们启动服务器,并输出localhost:8080/hello,会在3s之后响应的success。

此时,我们可以标识service方法为异步方法,即在AysncService中的hello方法上标识@Aysnc注解,同时在启动入口上标识@EnableAysnc注解:

package com.gong.spingbootes;

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

@EnableAsync
@SpringBootApplication
public class SpingbootEsApplication {

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

}

这时,我们再访问localhost:8080/hello,就不会在3s之后才响应了,而是立刻响应。

原文地址:https://www.cnblogs.com/xiximayou/p/12298392.html