Async异步处理【Springboot】

简单实现异步处理

①. 先建立一个controller目录,再建一个AsynController.java

package com.gql.controller;

import com.gql.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author gql
 * @date 2021/11/26 - 23:04
 */
@RestController
public class AsyncController
{
    @Autowired
    AsyncService asyncService;
    @RequestMapping("/hello")
    public String hello(){
      asyncService.hello();
      return "ok";
    }
}

②.建立一个service目录,再建立一个AsynController.java

package com.gql.service;

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

/**
 * @author gql
 * @date 2021/11/26 - 23:03
 */
@Service
public class AsyncService {

    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        System.out.println("数据加载中");
    }

}

③ 启动项目

package com.gql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication
public class SpringbootAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAsyncApplication.class, args);
    }

}

④ 效果

1.在三秒以后我们idea的console会显示

在这里插入图片描述

2.然后页面这时候三秒后也会显示

在这里插入图片描述
但是一般这样我们前端肯定会很难受啊,要等一会(线程等待)才能显示页面
所以就压有一个方法来解决这个问题,你访问localhost:8080/hello
会直接显示前端页面,但是我们的idea显示还是会在三秒以后才出现下面的画面
在这里插入图片描述
这是怎么实现的那,其实很简单
在我们调用的方法上面加入注解@Async

   @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();

        }
        System.out.println("数据加载中");
    }

然后在我们启动的项目(主项目)里面加入@EnableAsync来开启异步注释功能

@EnableAsync
@SpringBootApplication
public class SpringbootAsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootAsyncApplication.class, args);
    }

}

这样我们就可以,先出现前端ok页面(秒刷新),三秒后再idea的console才出现数据加载中
实现起来也是相当简单

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爪哇贡尘拾Miraitow

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值