等待 EC2 实例启动
Wait for EC2 instance to start
我有一个运行我的服务的自定义 AMI。使用 AWS Java SDK,我使用来自 AMI 的 RunInstancesRequest
创建了一个 EC2 实例。现在,在我开始使用我的服务之前,我必须确保新创建的实例已启动并且 运行。我使用以下方式轮询实例:
var transitionCompleted = false
while (!transitionCompleted) {
val currentState = instance.getState.getName
if (currentState == desiredState) {
transitionCompleted = true
}
if(!transitionCompleted) {
try {
Thread.sleep(TRANSITION_INTERVAL)
} catch {
case e: InterruptedException => e.printStackTrace()
}
}
}
因此,当实例的 currentState
变为 desiredState
(即 running
)时,我得到实例已准备就绪的状态。然而,任何新创建的实例,尽管处于 running
状态,仍无法立即使用,因为它仍在初始化。
如何确保我 return 仅当我能够访问实例及其服务时?是否需要进行任何特定的状态检查?
PS: 我使用 Scala
您正在检查实例 state, while what you are actually interested in are the instance status checks. You could use describeInstanceStatus
method from the Amazon Java SDK, but instead of implementing your own polling (in a non-idiomatic Scala) it's better to use a ready solution from the SDK: the EC2 waiters。
import com.amazonaws.services.ec2._, model._, waiters._
val ec2client: AmazonEC2 = ...
val request = new DescribeInstanceStatusRequest().withInstanceIds(instanceID)
ec2client.waiters.instanceStatusOk.run(
new WaiterParameters()
.withRequest(request)
// Optionally, you can tune the PollingStrategy:
// .withPollingStrategy(...)
)
)
要自定义服务员的轮询延迟和重试策略,请查看 PollingStrategy
文档。
我有一个运行我的服务的自定义 AMI。使用 AWS Java SDK,我使用来自 AMI 的 RunInstancesRequest
创建了一个 EC2 实例。现在,在我开始使用我的服务之前,我必须确保新创建的实例已启动并且 运行。我使用以下方式轮询实例:
var transitionCompleted = false
while (!transitionCompleted) {
val currentState = instance.getState.getName
if (currentState == desiredState) {
transitionCompleted = true
}
if(!transitionCompleted) {
try {
Thread.sleep(TRANSITION_INTERVAL)
} catch {
case e: InterruptedException => e.printStackTrace()
}
}
}
因此,当实例的 currentState
变为 desiredState
(即 running
)时,我得到实例已准备就绪的状态。然而,任何新创建的实例,尽管处于 running
状态,仍无法立即使用,因为它仍在初始化。
如何确保我 return 仅当我能够访问实例及其服务时?是否需要进行任何特定的状态检查?
PS: 我使用 Scala
您正在检查实例 state, while what you are actually interested in are the instance status checks. You could use describeInstanceStatus
method from the Amazon Java SDK, but instead of implementing your own polling (in a non-idiomatic Scala) it's better to use a ready solution from the SDK: the EC2 waiters。
import com.amazonaws.services.ec2._, model._, waiters._
val ec2client: AmazonEC2 = ...
val request = new DescribeInstanceStatusRequest().withInstanceIds(instanceID)
ec2client.waiters.instanceStatusOk.run(
new WaiterParameters()
.withRequest(request)
// Optionally, you can tune the PollingStrategy:
// .withPollingStrategy(...)
)
)
要自定义服务员的轮询延迟和重试策略,请查看 PollingStrategy
文档。