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

}
相关推荐
Suxing93 小时前
C语言基础分享:从“租房”到“拆迁”,C语言动态内存管理
java·数据结构·算法
减瓦3 小时前
别让 Java 版本选择变成生产事故
java
ikun_文3 小时前
Java集合框架Collection拓展进阶
java·java ee
云烟成雨TD3 小时前
Micrometer 系列【63】统一观测:基于 Spring Boot 的生产级演示案例 | 基于 OTLP 集成 Prometheus + Jaeger
spring boot·云原生·prometheus
码匠许师傅4 小时前
【C++ 面试真题】聊聊 C++ 的虚函数和多态
java·c++·面试
csdn2015_4 小时前
springboot +mybatis 查询myql开启程序级别缓存
spring boot·缓存·mybatis
chuan.bai4 小时前
Java RAG 实战(第 8 篇):Spring Boot RAG 查询 API
java·spring boot·贪心算法
FlyWIHTSKY4 小时前
idea中集成claude功能
java·ide·人工智能·intellij-idea·cloudera
Java成神之路-4 小时前
Spring AI 统一结构化返回:ChatModel / ChatClient 两种实现方式
java·springaialibaba
Mr. zhihao4 小时前
深度解析:为什么Java序列化需要搭配ByteArrayOutputStream?IO装饰器模式的精妙设计
java·开发语言·装饰器模式