2012-04-29 159 views
3

在AWS中創建負載均衡器作爲項目的一部分,我需要在亞馬遜AWS上創建新的負載均衡器。 我需要使用java sdk來完成如何在AWS中使用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"); 

回答

13

以及finelly我得到它:

首先創建一個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); 

和你做......