Springboot中异步任务的示例分析

WBOY
WBOY 转载
2023-05-10 23:31:04 879浏览

异步任务

启动类

@MapperScan("com.topcheer.*.*.dao")
@SpringBootApplication
@EnableCaching
@EnableRabbit
@EnableAsync
public class Oss6Application {
  public static void main(String[] args) {
    SpringApplication.run(Oss6Application.class, args);
  }
}

Controller层

/**
 * @author WGR
 * @create 2019/10/12 -- 21:53
 */
@RestController
public class AsynController {

  @Autowired
  AsynService asyncService;

  @GetMapping("/hello")
  public String hello(){
    asyncService.hello();
    return "success";
  }
}

Service层

/**
 * @author WGR
 * @create 2019/10/12 -- 21:52
 */
@Service
public class AsynService {

  //告诉Spring这是一个异步方法
  @Async
  public void hello() {
    try {
      Thread.sleep(3000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("处理数据中...");
  }

}

测试结果:

页面直接显示success,控制台过3秒显示处理数据中...

以上就是Springboot中异步任务的示例分析的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:亿速云,如有侵犯,请联系admin@php.cn删除