SpringBoot 使用 @Async 实现异步操作
如何实现异步方法调用,很多人首先会想到使用线程或者线程池技术,springboot中有一个很简单的方法可以实现异步方法调用,那就是在方法上使用@Async注解
启动类添加 @EnableAsync
注解
package com.zyxx;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import tk.mybatis.spring.annotation.MapperScan;
/**
* 项目启动类
*
* @author Tellsea
* @date 2019/7/13
*/
@EnableAsync
@SpringBootApplication
@MapperScan("com.zyxx.*.mapper")
public class SkeletonApplication {
public static void main(String[] args) {
SpringApplication.run(SkeletonApplication.class, args);
}
}
Controller
在 com.zyxx.customized
包中,创建 controller
包,然后创建 AsyncController
控制器
package com.zyxx.customized.controller;
import com.zyxx.customized.service.AsyncService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.Future;
/**
* 异步方法示例 控制器
*
* @author: Tellsea
* @date: 2019/09/10
*/
@Api(tags = "异步方法示例")
@Slf4j
@RestController
@RequestMapping("async")
public class AsyncController {
@Autowired
private AsyncService asyncService;
@ApiOperation("测试异步")
@GetMapping("example")
public String example() {
Future<String> future = asyncService.exampleAsync();
System.out.println(future);
return "success";
}
}
Service
在 com.zyxx.customized
包中,创建 service
包,然后创建 AsyncService
接口
package com.zyxx.customized.service;
import java.util.concurrent.Future;
/**
* 异步方法示例 接口层
*
* @author: Tellsea
* @date: 2019/09/10
*/
public interface AsyncService {
/**
* 异步方法测试案例
*
* @return
*/
Future<String> exampleAsync();
}
ServiceImpl
在 com.zyxx.customized
包中,创建 service.impl
包,然后创建 AsyncServiceImpl
实现类
package com.zyxx.customized.service.impl;
import com.zyxx.customized.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import java.util.concurrent.Future;
/**
* 异步方法 实现类
*
* @author: Tellsea
* @date: 2019/09/10
*/
@Service
public class AsyncServiceImpl implements AsyncService {
@Async
@Override
public Future<String> exampleAsync() {
try {
Thread.sleep(10000);
// 方法体,这里是异步执行的
System.out.println(111111);
} catch (InterruptedException e) {
e.printStackTrace();
}
return new AsyncResult<>("exampleAsync 执行完毕");
}
}
最后,调用接口,会直接返回字符串 success,等待十秒后,异步方法才会执行完成