作为项目的一部分,我需要在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);
你完成了...