这里我试图列出可用的实例。但是当我运行代码时,我收到错误消息为"无法通过区域提供程序链找到区域。必须在构建器或设置环境中提供显式区域以提供区域。"
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.DescribeInstancesRequest;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
@Controller
public class EC2InstancesController {
@RequestMapping(value="/getAllInstances", produces = {"application/json"},
consumes = {"application/json"}, method = RequestMethod.GET)
public List<Instance> getAllInstances(){
final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
boolean done = false;
while(!done) {
DescribeInstancesRequest request = new DescribeInstancesRequest();
DescribeInstancesResult response = ec2.describeInstances(request);
for(Reservation reservation : response.getReservations()) {
for(Instance instance : reservation.getInstances()) {
System.out.printf(
"Found reservation with id %s, " +
"AMI %s, " +
"type %s, " +
"state %s " +
"and monitoring state %s",
instance.getInstanceId(),
instance.getImageId(),
instance.getInstanceType(),
instance.getState().getName(),
instance.getMonitoring().getState());
}
}
request.setNextToken(response.getNextToken());
if(response.getNextToken() == null) {
done = true;
}
}
return null;
}
}
当我尝试从POSTMAN命中此端点时,我收到以下错误
{
"timestamp": 1498107927641,
"status": 500,
"error": "Internal Server Error",
"exception": "com.amazonaws.SdkClientException",
"message": "Unable to find a region via the region provider chain. Must provide an explicit region in the builder or setup environment to supply a region.",
"path": "/getAllInstances"
}
我还在上面添加了以下代码,但仍然从POSTMAN rest客户端收到相同的错误消息。
Region region = Region.getRegion(Regions.US_EAST_1);
ec2.setRegion(region);
有人可以帮助我吗?感谢..
答案 0 :(得分:0)
哪个版本的JAVA AWS SDK?
从Aws SDK 1.11.113开始,setRegion被取消了。
https://aws.amazon.com/blogs/developer/client-constructors-now-deprecated/
所以你需要在AWS Credentials中设置区域,或者你需要使用Method getCurrentRegion()来获取区域
参考:http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/regions/Regions.html
答案 1 :(得分:0)
通过使用标准构建器
更改默认的“客户端”构建器,它对我有用final AmazonEC2 ec2 = AmazonEC2ClientBuilder.standard().withRegion(Regions.AP_SOUTH_1).build();