使用@Async实现异步调用

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Leon_Jinhai_Sun/article/details/102763250
package com.learn.service;

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

@Service
public class User01Service {

    @Async
    public void sedSms() {
        System.out.println("##sedSms##开始执行..  2");
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                // TODO: handle exception
            }
            System.out.println("i:" + i);
        }
        System.out.println("##sedSms##结束执行..  3");
    }

}
package com.learn.controller;

import com.learn.service.User01Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class IndexController {

    @Autowired
    private User01Service user01Service;

    @ResponseBody
    @RequestMapping("/sedSms")
    public String sedSms() {
        System.out.println("###indexController### 1");
        user01Service.sedSms();
        System.out.println("###indexController### 4");
        return "success";
    }

}
package com.learn;

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

@EnableAsync
@SpringBootApplication
public class SpringbootQuick2Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootQuick2Application.class, args);
    }
}
###indexController### 1
2019-10-27 01:36:58.866  INFO 13208 --- [nio-8080-exec-1] 
###indexController### 4
2019-10-27 01:36:58.867  INFO 13208 --- [nio-8080-exec-1] com.learn.app.WebLogAspect 
             : RESPONSE : success
##sedSms##开始执行..  2
i:0
i:1
i:2
i:3
i:4
##sedSms##结束执行..  3

猜你喜欢

转载自blog.csdn.net/Leon_Jinhai_Sun/article/details/102763250