前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springboot任务之异步任务

springboot任务之异步任务

作者头像
西西嘛呦
发布2020-08-26 15:41:10
4380
发布2020-08-26 15:41:10
举报
文章被收录于专栏:数据分析与挖掘

先看同步的情况:

AysncService.java

代码语言:javascript
复制
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

代码语言:javascript
复制
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注解:

代码语言:javascript
复制
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之后才响应了,而是立刻响应。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-02-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档