springboot异步任务

在Service类声明一个注解@Async作为异步方法的标识

java 复制代码
package com.qf.sping09test.service;

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

@Service
public class AsyncService {

    //告诉spring这是一个异步的方法
    @Async
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("数据正在处理...");
    }


}

controller

java 复制代码
package com.qf.sping09test.controller;

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

@RestController
public class AsyncController {

    @Autowired
    AsyncService asyncService;

    @RequestMapping("/hello")
    public String hello(){
          asyncService.hello();//停止三秒,转圈
          return "ok";
    }


}

主启动类需要加一个注解

java 复制代码
package com.qf.sping09test;

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

@SpringBootApplication
@EnableAsync
public class Sping09TestApplication {

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

}
相关推荐
NE_STOP8 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园8 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆8 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
霸道流氓气质8 小时前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
小宇宙Zz9 小时前
Maven依赖冲突
java·服务器·maven
swordbob9 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
于先生吖9 小时前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
咖啡八杯9 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网9 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠9 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea