SpringBoot:@Async实现异步方法调用
一,@Async注解
@Async是SprngBoot框架提供的框架内部已经整合好的异步调用方式。在入口处开启异步调用按钮,然后在调用方法上直接添加该注解,就可以自动实现异步调用。
二,异步发送类
package com.gupao.springboot.test.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* SpringBoot异步调用测试
* @author pj_zhang
* @create 2018-12-25 21:19
**/
@RestController
@Slf4j
public class AsyncController {
// 注入消费者类
@Autowired
private ProcessorController processorController;
@RequestMapping("/sendMlessage")
public String sendMessage() {
log.info("start sendMessage ====== " + 1);
// 该方法添加了@Async注解, 实现异步调用
processorController.processor();
log.info("end sendMessage ===== " + 4);
return "SUCCESS";
}
}
三,异步接收类
package com.gupao.springboot.test.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
/**
* 异步接收类
* @author pj_zhang
* @create 2018-12-25 21:22
**/
@Controller
@Slf4j
public class ProcessorController {
// 添加异步注解
@Async
public void processor() {
log.info("start processor ====== " + 2);
try {
// 睡眠2S查看异步效果
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("end processor ====== " + 3);
}
}
四,SpringBoot程序主入口开启异步
package com.gupao.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
// 开启异步消息
@EnableAsync
public class GupaoSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(GupaoSpringbootApplication.class, args);
}
}
五,效果演示
\* 发送消息线程沉睡1S,再次尝试
@RequestMapping("/sendMlessage")
public String sendMessage() {
log.info("start sendMessage ====== " + 1);
processorController.processor();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("end sendMessage ===== " + 4);
return "SUCCESS";
}
还没有评论,来说两句吧...