首页技术栈归档照片墙音乐日记随想收藏夹友链留言关于

异步任务

写作时间:2026-07-08

异步任务

AsyncController

@RestController
public class AsyncController {

    @Autowired
   AsyncService service;

    @GetMapping("/hello")
    public String hello(){
        service.hello();
        return "OK";
    }
}

AsyncService

package com.yuan.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {

    @Async //告诉Spring 这是一个异步方法
    public void hello(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("操作成功");
    }
}

DemoApplication启动类

package com.yuan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync//开启异步注解功能
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}
avatar

yuanyourdomain

写代码,做研究,记录生活。

RECOMMENDED

MyBatis 动态 SQL

2026-07-08

Nginx 基础入门

2026-07-08

Maven 多模块与私服

2026-07-08