springboot异步任务

异步任务

【为什么要异步任务】

  • 前端需要加载一个页面,里面存在很多数据,需要从后端调取,调取数据很慢
  • 前端先加载一个其他的页面,后端再调取数据,两者异步
  • 当两者都加载完后,界面就显示出来了

举例

  • 调取index.html但是存在数据很多,加载需要等待时间
  • 在login.html后,调取数据,先去调取一个正在加载的界面
  • 然后等待调取数据成功后,再次调用index.html

SpringBoot异步任务

步骤

编写一个Service【关于线程的】AsyncService

@Service
public class AsyncService {

    @Async
    public void hello(){
        System.out.println("数据正在读取");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("数据读取完成");
    }
}

写一个Controller

@Controller
public class AsyncController {
    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        asyncService.hello();
        return "okkkk";
    }
}

开启异步注解功能

@EnableAsync

结果

先显示读取数据,同时转圈圈,3秒后显示出页面,然后控制台输出数据读取完成

  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值