Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen
Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.
Gunakan CreateLoadBalancer
dengan AWS SDK atau CLI
Contoh kode berikut menunjukkan cara menggunakanCreateLoadBalancer
.
Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:
- .NET
-
- AWS SDK for .NET
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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]; }
-
Untuk API detailnya, lihat CreateLoadBalancerdi AWS SDK for .NET APIReferensi.
-
- CLI
-
- AWS CLI
-
Contoh 1: Untuk membuat penyeimbang beban yang menghadap ke Internet
create-load-balancer
Contoh berikut membuat Application Load Balancer yang menghadap Internet dan mengaktifkan Availability Zones untuk subnet yang ditentukan.aws elbv2 create-load-balancer \ --name
my-load-balancer
\ --subnetssubnet-b7d581c0
subnet-8360a9e7
Output:
{ "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" } ] }
Untuk informasi selengkapnya, lihat Tutorial: Membuat Application Load Balancer menggunakan Panduan Pengguna untuk Application Load Balancers. AWS CLI
Contoh 2: Untuk membuat penyeimbang beban internal
create-load-balancer
Contoh berikut membuat Application Load Balancer internal dan mengaktifkan Availability Zones untuk subnet yang ditentukan.aws elbv2 create-load-balancer \ --name
my-internal-load-balancer
\ --schemeinternal
\ --subnetssubnet-b7d581c0
subnet-8360a9e7
Output:
{ "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" } ] }
Untuk informasi selengkapnya, lihat Tutorial: Membuat Application Load Balancer menggunakan Panduan Pengguna untuk Application Load Balancers. AWS CLI
Contoh 3: Untuk membuat Network Load Balancer
create-load-balancer
Contoh berikut membuat Network Load Balancer yang menghadap Internet dan mengaktifkan Availability Zone untuk subnet yang ditentukan. Ini menggunakan pemetaan subnet untuk mengaitkan alamat IP Elastis yang ditentukan dengan antarmuka jaringan yang digunakan oleh node penyeimbang beban untuk Availability Zone.aws elbv2 create-load-balancer \ --name
my-network-load-balancer
\ --typenetwork
\ --subnet-mappingsSubnetId=subnet-b7d581c0,AllocationId=eipalloc-64d5890a
Output:
{ "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" } ] }
Untuk informasi selengkapnya, lihat Tutorial: Membuat Network Load Balancer menggunakan Panduan Pengguna untuk Network Load Balancer. AWS CLI
Contoh 4: Untuk membuat Load Balancer Gateway
create-load-balancer
Contoh berikut membuat Load Balancer Gateway dan mengaktifkan Availability Zones untuk subnet yang ditentukan.aws elbv2 create-load-balancer \ --name
my-gateway-load-balancer
\ --typegateway
\ --subnetssubnet-dc83f691
subnet-a62583f9
Output:
{ "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" } ] }
Untuk informasi selengkapnya, lihat Memulai Load Balancer Gateway menggunakan Panduan Pengguna untuk Penyeimbang Beban Gateway. AWS CLI
-
Untuk API detailnya, lihat CreateLoadBalancer
di Referensi AWS CLI Perintah.
-
- Java
-
- SDKuntuk Java 2.x
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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 ""; }
-
Untuk API detailnya, lihat CreateLoadBalancerdi AWS SDK for Java 2.x APIReferensi.
-
- JavaScript
-
- SDKuntuk JavaScript (v3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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] }, );
-
Untuk API detailnya, lihat CreateLoadBalancerdi AWS SDK for JavaScript APIReferensi.
-
- PowerShell
-
- Alat untuk PowerShell
-
Contoh 1: Contoh ini menciptakan penyeimbang beban Aplikasi yang menghadap internet baru dengan dua subnet.
New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'
Output:
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
-
Untuk API detailnya, lihat CreateLoadBalancerdi AWS Tools for PowerShell Referensi Cmdlet.
-
- Python
-
- SDKuntuk Python (Boto3)
-
catatan
Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara pengaturan dan menjalankannya di Repositori Contoh Kode 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
-
Untuk API detailnya, lihat CreateLoadBalancer AWSSDKReferensi Python (Boto3). API
-