码迷,mamicode.com
首页 > 编程语言 > 详细

springboot任务之异步任务

时间:2020-02-12 13:19:06      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:rup   ble   service   rgs   ica   success   conf   cal   服务   

先看同步的情况:

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之后才响应了,而是立刻响应。

springboot任务之异步任务

标签:rup   ble   service   rgs   ica   success   conf   cal   服务   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!