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

}
相关推荐
金牌归来发现妻女流落街头10 分钟前
【从SpringBoot到SpringCloud】
java·spring boot·spring cloud
毅炼11 分钟前
Java 基础常见问题总结(4)
java·后端
张3蜂12 分钟前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
GR23423423 分钟前
2025年影视仓TV+手机官方版 内置地址源支持高清直播
java·智能手机·软件
皮卡丘不断更24 分钟前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
程序员清风1 小时前
北京回长沙了,简单谈谈感受!
java·后端·面试
lucky67071 小时前
Spring Boot集成Kafka:最佳实践与详细指南
spring boot·kafka·linq
何中应1 小时前
请求头设置没有生效
java·后端
Coder_Boy_1 小时前
基于Spring AI的分布式在线考试系统-事件处理架构实现方案
人工智能·spring boot·分布式·spring
亓才孓1 小时前
[JDBC]批处理
java