AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
与 AWS SDK或CreateLoadBalancer
一起使用 CLI
以下代码示例演示如何使用 CreateLoadBalancer
。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- .NET
-
- AWS SDK for .NET
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /// <summary> /// Create an Elastic Load Balancing load balancer that uses the specified subnets /// and forwards requests to the specified target group. /// </summary> /// <param name="name">The name for the new load balancer.</param> /// <param name="subnetIds">Subnets for the load balancer.</param> /// <param name="targetGroup">Target group for forwarded requests.</param> /// <returns>The new LoadBalancer object.</returns> public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup) { var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync( new CreateLoadBalancerRequest() { Name = name, Subnets = subnetIds }); var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn; // Wait for load balancer to be available. var loadBalancerReady = false; while (!loadBalancerReady) { try { var describeResponse = await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync( new DescribeLoadBalancersRequest() { Names = new List<string>() { name } }); var loadBalancerState = describeResponse.LoadBalancers[0].State.Code; loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active; } catch (LoadBalancerNotFoundException) { loadBalancerReady = false; } Thread.Sleep(10000); } // Create the listener. await _amazonElasticLoadBalancingV2.CreateListenerAsync( new CreateListenerRequest() { LoadBalancerArn = loadBalancerArn, Protocol = targetGroup.Protocol, Port = targetGroup.Port, DefaultActions = new List<Action>() { new Action() { Type = ActionTypeEnum.Forward, TargetGroupArn = targetGroup.TargetGroupArn } } }); return createLbResponse.LoadBalancers[0]; }
-
有关API详细信息,请参阅 “AWS SDK for .NET API参考 CreateLoadBalancer” 中的。
-
- CLI
-
- AWS CLI
-
示例 1:创建面向 Internet 的负载均衡器
以下
create-load-balancer
示例创建一个面向 Internet 的应用程序负载均衡器,并为指定的子网启用可用区。aws elbv2 create-load-balancer \ --name
my-load-balancer
\ --subnetssubnet-b7d581c0
subnet-8360a9e7
输出:
{ "LoadBalancers": [ { "Type": "application", "Scheme": "internet-facing", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "ZoneName": "us-west-2a", "SubnetId": "subnet-8360a9e7" }, { "ZoneName": "us-west-2b", "SubnetId": "subnet-b7d581c0" } ], "CreatedTime": "2017-08-25T21:26:12.920Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "my-load-balancer-424835706.us-west-2.elb.amazonaws.com", "SecurityGroups": [ "sg-5943793c" ], "LoadBalancerName": "my-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" } ] }
有关更多信息,请参阅教程:使用应用程序负载均衡器用户指南 AWS CLI中的创建应用程序负载均衡器。
示例 2:创建内部负载均衡器
以下
create-load-balancer
示例创建一个内部应用程序负载均衡器,并为指定的子网启用可用区。aws elbv2 create-load-balancer \ --name
my-internal-load-balancer
\ --schemeinternal
\ --subnetssubnet-b7d581c0
subnet-8360a9e7
输出:
{ "LoadBalancers": [ { "Type": "application", "Scheme": "internal", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "ZoneName": "us-west-2a", "SubnetId": "subnet-8360a9e7" }, { "ZoneName": "us-west-2b", "SubnetId": "subnet-b7d581c0" } ], "CreatedTime": "2016-03-25T21:29:48.850Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "internal-my-internal-load-balancer-1529930873.us-west-2.elb.amazonaws.com", "SecurityGroups": [ "sg-5943793c" ], "LoadBalancerName": "my-internal-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-internal-load-balancer/5b49b8d4303115c2" } ] }
有关更多信息,请参阅教程:使用应用程序负载均衡器用户指南 AWS CLI中的创建应用程序负载均衡器。
示例 3:创建网络负载均衡器
以下
create-load-balancer
示例创建一个面向 Internet 的网络负载均衡器,并为指定的子网启用可用区。它使用子网映射,将指定的弹性 IP 地址与可用区的负载均衡器节点使用的网络接口相关联。aws elbv2 create-load-balancer \ --name
my-network-load-balancer
\ --typenetwork
\ --subnet-mappingsSubnetId=subnet-b7d581c0,AllocationId=eipalloc-64d5890a
输出:
{ "LoadBalancers": [ { "Type": "network", "Scheme": "internet-facing", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "LoadBalancerAddresses": [ { "IpAddress": "35.161.207.171", "AllocationId": "eipalloc-64d5890a" } ], "ZoneName": "us-west-2b", "SubnetId": "subnet-5264e837" } ], "CreatedTime": "2017-10-15T22:41:25.657Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "my-network-load-balancer-5d1b75f4f1cee11e.elb.us-west-2.amazonaws.com", "LoadBalancerName": "my-network-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/net/my-network-load-balancer/5d1b75f4f1cee11e" } ] }
有关更多信息,请参阅教程:使用网络负载均衡器用户指南 AWS CLI中的创建网络负载均衡器。
示例 4:创建网关负载均衡器
以下
create-load-balancer
示例创建一个网关负载均衡器,并为指定的子网启用可用区。aws elbv2 create-load-balancer \ --name
my-gateway-load-balancer
\ --typegateway
\ --subnetssubnet-dc83f691
subnet-a62583f9
输出:
{ "LoadBalancers": [ { "Type": "gateway", "VpcId": "vpc-838475fe", "AvailabilityZones": [ { "ZoneName": "us-east-1b", "SubnetId": "subnet-a62583f9" }, { "ZoneName": "us-east-1a", "SubnetId": "subnet-dc83f691" } ], "CreatedTime": "2021-07-14T19:33:43.324000+00:00", "LoadBalancerName": "my-gateway-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:loadbalancer/gwy/my-gateway-load-balancer/dfbb5a7d32cdee79" } ] }
有关更多信息,请参阅网关负载均衡器用户指南 AWS CLI中的网关负载均衡器入门。
-
有关API详细信息,请参阅 “CreateLoadBalancer AWS CLI
命令参考”。
-
- Java
-
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /* * Creates an Elastic Load Balancing load balancer that uses the specified * subnets * and forwards requests to the specified target group. */ public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port, String protocol) { try { List<String> subnetIdStrings = subnetIds.stream() .map(Subnet::subnetId) .collect(Collectors.toList()); CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder() .subnets(subnetIdStrings) .name(lbName) .scheme("internet-facing") .build(); // Create and wait for the load balancer to become available. CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest); String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn(); ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter(); DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder() .loadBalancerArns(lbARN) .build(); System.out.println("Waiting for Load Balancer " + lbName + " to become available."); WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter .waitUntilLoadBalancerAvailable(request); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Load Balancer " + lbName + " is available."); // Get the DNS name (endpoint) of the load balancer. String lbDNSName = lsResponse.loadBalancers().get(0).dnsName(); System.out.println("*** Load Balancer DNS Name: " + lbDNSName); // Create a listener for the load balance. Action action = Action.builder() .targetGroupArn(targetGroupARN) .type("forward") .build(); CreateListenerRequest listenerRequest = CreateListenerRequest.builder() .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn()) .defaultActions(action) .port(port) .protocol(protocol) .defaultActions(action) .build(); getLoadBalancerClient().createListener(listenerRequest); System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group " + targetGroupARN); // Return the load balancer DNS name. return lbDNSName; } catch (ElasticLoadBalancingV2Exception e) { e.printStackTrace(); } return ""; }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 CreateLoadBalancer” 中的。
-
- JavaScript
-
- SDK对于 JavaScript (v3)
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new CreateLoadBalancerCommand({ Name: NAMES.loadBalancerName, Subnets: state.subnets, }), ); state.loadBalancerDns = LoadBalancers[0].DNSName; state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn; await waitUntilLoadBalancerAvailable( { client }, { Names: [NAMES.loadBalancerName] }, );
-
有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 CreateLoadBalancer” 中的。
-
- PowerShell
-
- 用于 PowerShell
-
示例 1:此示例创建了具有两个子网的面向互联网的新应用程序负载均衡器。
New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'
输出:
AvailabilityZones : {us-east-1b, us-east-1a} CanonicalHostedZoneId : Z35SXDOTRQ7X7K CreatedTime : 12/28/19 2:58:03 PM DNSName : New-Test-ALB-1391502222.us-east-1.elb.amazonaws.com IpAddressType : ipv4 LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/New-Test-ALB/dab2e4d90eb51493 LoadBalancerName : New-Test-ALB Scheme : internet-facing SecurityGroups : {sg-07c3414abb8811cbd} State : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState Type : application VpcId : vpc-2cfd7000
-
有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考CreateLoadBalancer中的。
-
- Python
-
- SDK适用于 Python (Boto3)
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 class ElasticLoadBalancerWrapper: """Encapsulates Elastic Load Balancing (ELB) actions.""" def __init__(self, elb_client: boto3.client): """ Initializes the LoadBalancer class with the necessary parameters. """ self.elb_client = elb_client def create_load_balancer( self, load_balancer_name: str, subnet_ids: List[str], ) -> Dict[str, Any]: """ Creates an Elastic Load Balancing load balancer that uses the specified subnets and forwards requests to the specified target group. :param load_balancer_name: The name of the load balancer to create. :param subnet_ids: A list of subnets to associate with the load balancer. :return: Data about the newly created load balancer. """ try: response = self.elb_client.create_load_balancer( Name=load_balancer_name, Subnets=subnet_ids ) load_balancer = response["LoadBalancers"][0] log.info(f"Created load balancer '{load_balancer_name}'.") waiter = self.elb_client.get_waiter("load_balancer_available") log.info( f"Waiting for load balancer '{load_balancer_name}' to be available..." ) waiter.wait(Names=[load_balancer_name]) log.info(f"Load balancer '{load_balancer_name}' is now available!") except ClientError as err: error_code = err.response["Error"]["Code"] log.error( f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}" ) if error_code == "DuplicateLoadBalancerNameException": log.error( f"A load balancer with the name '{load_balancer_name}' already exists. " "Load balancer names must be unique within the AWS region. " "Please choose a different name and try again." ) if error_code == "TooManyLoadBalancersException": log.error( "The maximum number of load balancers has been reached in this account and region. " "You can delete unused load balancers or request an increase in the service quota from AWS Support." ) log.error(f"Full error:\n\t{err}") else: return load_balancer
-
有关API详细信息,请参阅CreateLoadBalancer中的 AWS SDKPython (Boto3) API 参考。
-