zoukankan      html  css  js  c++  java
  • springBoot项目中任务---开启异步任务

    Controller层代码:

    @RestController
    public class AsyncController {
    
        @Autowired
        private AsyncService asyncService;
    
        @RequestMapping("/hello")
        public String hello(){
            asyncService.hello();//停止三秒,转圈
            return "ok";
        }
    }

    Service层代码:

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

    启动类上加上注解;

    @EnableAsync //开启异步注解功能
    @SpringBootApplication
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }

    总结:就是两步;第一步,在方法上加上@Async注解;第二步,在启动类上加上@EnableAsync即可;

    效果,进入hello方法,浏览器不会立刻进入,会转圈三秒再显示ok;

     
  • 相关阅读:
    各位相加
    模板方法设计模式
    581. Shortest Unsorted Continuous Subarray
    LeetCode
    判断质数
    整除问题
    A+B+C问题
    juery 安全加固 集合
    丁洪波 -- 不要“ 总是拿着微不足道的成就来骗自己”
    avalon源码阅读(1)
  • 原文地址:https://www.cnblogs.com/xie-qi/p/14711323.html
Copyright © 2011-2022 走看看