如何使用AWS java sdk在AWS中创建负载均衡器
作者:互联网
作为项目的一部分,我需要在amazon AWS上创建一个新的负载均衡器.
我需要使用java sdk来完成它
如何使用代码设置负载均衡器?
这是我到目前为止没有成功的尝试.
//create load balancer
CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest();
lbRequest.setLoadBalancerName("loader");
List<Listener> listeners = new ArrayList<Listener>(1);
listeners.add(new Listener("HTTP", 80, 80));
lbRequest.withAvailabilityZones(availabilityZone1,availabilityZone2);
lbRequest.setListeners(listeners);
CreateLoadBalancerResult lbResult=new CreateLoadBalancerResult();
System.out.println("created load balancer loader");
解决方法:
好吧,我明白了:
首先创建一个elb客户端
AmazonElasticLoadBalancingClient elb = new AmazonElasticLoadBalancingClient(credentials);
然后
用它来发起请求
//create load balancer
CreateLoadBalancerRequest lbRequest = new CreateLoadBalancerRequest();
lbRequest.setLoadBalancerName("loader");
List<Listener> listeners = new ArrayList<Listener>(1);
listeners.add(new Listener("HTTP", 80, 80));
lbRequest.withAvailabilityZones(availabilityZone1,availabilityZone2);
lbRequest.setListeners(listeners);
CreateLoadBalancerResult lbResult=elb.createLoadBalancer(lbRequest);
System.out.println("created load balancer loader");
然后将您的实例注册到负载均衡器
//get the running instances
DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
List<Instance> instances = new ArrayList<Instance>();
for (Reservation reservation : reservations) {
instances.addAll(reservation.getInstances());
}
//get instance id's
String id;
List instanceId=new ArrayList();
List instanceIdString=new ArrayList();
Iterator<Instance> iterator=instances.iterator();
while (iterator.hasNext())
{
id=iterator.next().getInstanceId();
instanceId.add(new com.amazonaws.services.elasticloadbalancing.model.Instance(id));
instanceIdString.add(id);
}
//register the instances to the balancer
RegisterInstancesWithLoadBalancerRequest register =new RegisterInstancesWithLoadBalancerRequest();
register.setLoadBalancerName("loader");
register.setInstances((Collection)instanceId);
RegisterInstancesWithLoadBalancerResult registerWithLoadBalancerResult= elb.registerInstancesWithLoadBalancer(register);
你完成了……
标签:java,amazon-web-services,load-balancing,amazon-elb 来源: https://codeday.me/bug/20190713/1450903.html