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

}
相关推荐
曹牧3 分钟前
文档格式:OFD
java
豆角焖肉28 分钟前
Maven进阶与搭建私服
java·maven
空中湖29 分钟前
Spring AI Agent 编排:ReAct 模式 + 多 Agent 协作实战
人工智能·spring·react.js
大不点wow39 分钟前
Java序列化与反序列化:让对象走出JVM
java·开发语言·jvm
噢,我明白了43 分钟前
Java中日期和字符串的处理
java·开发语言·日期
dkbnull1 小时前
Spring Boot请求处理组件对比详解
java·spring boot
jun_bai1 小时前
Orthanc服务器使用java上传dicom影像文件
java·运维·服务器
顺风尿一寸1 小时前
记一次 Spring AOP 与定时任务引发的死锁排查
java
不能只会打代码1 小时前
Day 011 — Spring 全家桶深度拆解
spring boot·mybatis·spring aop·spring mvc·spring ioc
用户446139430271 小时前
从单体到微服务:我们项目的拆分思路和踩坑记录
java