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

}
相关推荐
盖世英雄酱5813611 小时前
Read timed out问题 排查
java·数据库·后端
狼爷11 小时前
破解 JetBrains 的学生,后来都成了它的 “推销员”:一场用习惯换市场的长期战
java·jetbrains
.豆鲨包11 小时前
【Android】Viewpager2实现无限轮播图
android·java
BXCQ_xuan11 小时前
软件工程实践二:Spring Boot 知识回顾
java·spring boot·后端
老赵的博客11 小时前
c++ unqiue指针
java·jvm·c++
wuxuanok12 小时前
SpringBoot -原理篇
java·spring boot·spring
柿蒂12 小时前
从if-else和switch,聊聊“八股“的作用
android·java·kotlin
云动雨颤12 小时前
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
数据库·spring boot·tomcat
二饭12 小时前
Spring Boot 项目启动报错:MongoSocketOpenException 连接被拒绝排查日记
java·spring boot·后端
懒虫虫~12 小时前
通过内存去重替换SQL中distinct,优化SQL查询效率
java·sql·慢sql治理