摘要:本文主要介绍在Springboot
环境中,启动的时候或者我们功能依赖于其他的服务,我们需要等待其他服务完成后才能执行我们的代码,这里提供一个更好的案例,便于大家在代码中使用。
WaitService
平常的时候,我们用的最多的就是
while Thread.sleep
来使用,这里用ScheduledExecutorService
来判断,更优雅一点
java
public class WaitService {
public Result packageApk(){
Result result = new Result();
ScheduledExecutorService executorService = new ScheduledThreadPoolExecutor(1,
ThreadFactoryBuilder.create().setNamePrefix("schedule-pool-package-apk-").setDaemon(true).build());
try {
CountDownLatch countDownLatch = new CountDownLatch(1);
Runnable runnable = () -> {
// 判断其他依赖项是否已经启动完成,这里用随机数1成功,0失败,其他表示还在等待
Random random = new Random();
int i = random.nextInt(10);
System.out.println("当前随机数:"+ i);
if(i == 1){
result.setSuccess(true);
countDownLatch.countDown();
}else if(i == 0){
result.setSuccess(false);
countDownLatch.countDown();
}
};
executorService.scheduleAtFixedRate(runnable, 5, 5, TimeUnit.SECONDS);
countDownLatch.await(5, TimeUnit.MINUTES);
} catch (Exception ex) {
result.setSuccess(false);
result.setMessage(ex.getMessage());
ex.printStackTrace();
} finally {
if(!executorService.isShutdown()){
executorService.shutdown();
}
}
return result;
}
@Data
public static class Result {
private Boolean success;
private String message;
}
public static void main(String[] args) {
WaitService waitService = new WaitService();
Result result = waitService.packageApk();
System.out.println("success="+result.getSuccess()+", message=" + result.getMessage());
}
}
结果
csharp
Connected to the target VM, address: '127.0.0.1:61037', transport: 'socket'
当前随机数:6
当前随机数:5
当前随机数:2
当前随机数:9
当前随机数:7
当前随机数:9
当前随机数:9
当前随机数:4
当前随机数:7
当前随机数:2
当前随机数:2
当前随机数:1
success=true, message=null