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

}
相关推荐
Pluchon3 分钟前
硅基计划4.0 算法 动态规划进阶
java·数据结构·算法·动态规划
会游泳的石头4 分钟前
Java 异步事务完成后的监听器:原理、实现与应用场景
java·开发语言·数据库
数智工坊4 分钟前
【操作系统-IO调度】
java·服务器·数据库
黎雁·泠崖7 分钟前
Java字符串进阶:StringBuilder+StringJoiner
java·开发语言
糖猫猫cc19 分钟前
Kite:Kotlin/Java 通用的全自动 ORM 框架
java·kotlin·springboot·orm
u01040583619 分钟前
Java微服务架构:设计模式与实践
java·微服务·架构
AI_567828 分钟前
测试用例“标准化”:TestRail实战技巧,从“用例编写”到“测试报告生成”
java·python·测试用例·testrail
Anastasiozzzz32 分钟前
LRU缓存是什么?&力扣相关题目
java·缓存·面试
麦兜*36 分钟前
SpringBoot集成Redis缓存,提升接口性能的五大实战策略
spring boot·redis·缓存
茶本无香1 小时前
@Scheduled(cron = “0 */5 * * * ?“) 详解
java·定时任务·scheduled