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";
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值