spring boot 异步执行耗时方法

  作者:记性不好的阁主

1、在启动类上添加开启异步注解



@EnableAsync
@SpringBootApplication
public class SpringBoot04taskApplication {

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

}



2、在Service层的方法上加上异步注解@Async


package com.laoxu.task.service.impl;

import com.laoxu.task.service.HelloService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class HelloServiceImpl implements HelloService {

@Override
@Async
public void sayHello() throws InterruptedException {
Thread.sleep(5000);
System.out.println("Hello World");
}
}



3、控制器调用Service层的方法


package com.laoxu.task.controller;

import com.laoxu.task.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

@Autowired
private HelloService helloService;

@GetMapping("/hello")
public String hello() throws InterruptedException {
helloService.sayHello();
return "success";
}
}



在5秒后打印Hello World


相关推荐

评论 抢沙发

表情

分类选择