zoukankan      html  css  js  c++  java
  • 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之后才响应了,而是立刻响应。

  • 相关阅读:
    Java零基础学习(四)JSP与Servlet
    Java零基础学习(三)封装继承多态
    vsftpd+nginx搭建图片服务器的一些问题
    1003. 我要通过!(20)(两种语言的运行时间差异)
    acm 1108 java做法
    acm 2020 用java实现
    acm 2519 java做法
    acm 2040 java做法
    acm 2003 java做法
    acm 2041 java的做法
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12298392.html
Copyright © 2011-2022 走看看