AWS 文档 AWS SDK示例 GitHub 存储库中还有更多SDK示例
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
与 AWS SDK或CreateTargetGroup
一起使用 CLI
以下代码示例演示如何使用 CreateTargetGroup
。
操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:
- .NET
-
- AWS SDK for .NET
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /// <summary> /// Create an Elastic Load Balancing target group. The target group specifies how the load balancer forwards /// requests to instances in the group and how instance health is checked. /// /// To speed up this demo, the health check is configured with shortened times and lower thresholds. In production, /// you might want to decrease the sensitivity of your health checks to avoid unwanted failures. /// </summary> /// <param name="groupName">The name for the group.</param> /// <param name="protocol">The protocol, such as HTTP.</param> /// <param name="port">The port to use to forward requests, such as 80.</param> /// <param name="vpcId">The Id of the Vpc in which the load balancer exists.</param> /// <returns>The new TargetGroup object.</returns> public async Task<TargetGroup> CreateTargetGroupOnVpc(string groupName, ProtocolEnum protocol, int port, string vpcId) { var createResponse = await _amazonElasticLoadBalancingV2.CreateTargetGroupAsync( new CreateTargetGroupRequest() { Name = groupName, Protocol = protocol, Port = port, HealthCheckPath = "/healthcheck", HealthCheckIntervalSeconds = 10, HealthCheckTimeoutSeconds = 5, HealthyThresholdCount = 2, UnhealthyThresholdCount = 2, VpcId = vpcId }); var targetGroup = createResponse.TargetGroups[0]; return targetGroup; }
-
有关API详细信息,请参阅 “AWS SDK for .NET API参考 CreateTargetGroup” 中的。
-
- CLI
-
- AWS CLI
-
示例 1:为 Application Load Balancer 创建目标组
以下
create-target-group
示例为应用程序负载均衡器创建目标组,以便您按实例 ID(目标类型为instance
)注册目标。此目标组使用HTTP协议、端口 80 和HTTP目标组的默认运行状况检查设置。aws elbv2 create-target-group \ --name
my-targets
\ --protocolHTTP
\ --port80
\ --target-typeinstance
\ --vpc-idvpc-3ac0fb5f
输出:
{ "TargetGroups": [ { "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067", "TargetGroupName": "my-targets", "Protocol": "HTTP", "Port": 80, "VpcId": "vpc-3ac0fb5f", "HealthCheckProtocol": "HTTP", "HealthCheckPort": "traffic-port", "HealthCheckEnabled": true, "HealthCheckIntervalSeconds": 30, "HealthCheckTimeoutSeconds": 5, "HealthyThresholdCount": 5, "UnhealthyThresholdCount": 2, "HealthCheckPath": "/", "Matcher": { "HttpCode": "200" }, "TargetType": "instance", "ProtocolVersion": "HTTP1", "IpAddressType": "ipv4" } ] }
有关更多信息,请参阅《应用程序负载均衡器用户指南》中的创建目标组。
示例 2:创建目标组以将流量从 Application Load Balancer 路由到 Lambda 函数
以下
create-target-group
示例为应用程序负载均衡器创建目标组,在其中目标为 Lambda 函数(目标类型为lambda
)。默认情况下,为此目标组禁用运行状况检查。aws elbv2 create-target-group \ --name
my-lambda-target
\ --target-typelambda
输出:
{ "TargetGroups": [ { "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-lambda-target/a3003e085dbb8ddc", "TargetGroupName": "my-lambda-target", "HealthCheckEnabled": false, "HealthCheckIntervalSeconds": 35, "HealthCheckTimeoutSeconds": 30, "HealthyThresholdCount": 5, "UnhealthyThresholdCount": 2, "HealthCheckPath": "/", "Matcher": { "HttpCode": "200" }, "TargetType": "lambda", "IpAddressType": "ipv4" } ] }
有关更多信息,请参阅应用程序负载均衡器用户指南中的 Lambda 函数作为目标。
示例 3:为 Network Load Balancer 创建目标组
以下
create-target-group
示例为网络负载均衡器创建目标组,以便您按 IP 地址(目标类型为ip
)注册目标。此目标组使用TCP协议、端口 80 和TCP目标组的默认运行状况检查设置。aws elbv2 create-target-group \ --name
my-ip-targets
\ --protocolTCP
\ --port80
\ --target-typeip
\ --vpc-idvpc-3ac0fb5f
输出:
{ "TargetGroups": [ { "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-ip-targets/b6bba954d1361c78", "TargetGroupName": "my-ip-targets", "Protocol": "TCP", "Port": 80, "VpcId": "vpc-3ac0fb5f", "HealthCheckEnabled": true, "HealthCheckProtocol": "TCP", "HealthCheckPort": "traffic-port", "HealthCheckIntervalSeconds": 30, "HealthCheckTimeoutSeconds": 10, "HealthyThresholdCount": 5, "UnhealthyThresholdCount": 2, "TargetType": "ip", "IpAddressType": "ipv4" } ] }
有关更多信息,请参阅《网络负载均衡器用户指南》中的创建目标组。
示例 4:创建目标组以将流量从网络负载均衡器路由到 Application Load Balancer
以下
create-target-group
示例为网络负载均衡器创建目标组,您将在其中将应用程序负载均衡器注册为目标(目标类型为alb
)。aws elbv2 create-target-group--name--portocol--port 80--target-type alb my-alb-target--vpc-id vpc-3ac0 TCP fb5f
输出:
{ "TargetGroups": [ { "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-alb-target/a3003e085dbb8ddc", "TargetGroupName": "my-alb-target", "Protocol": "TCP", "Port": 80, "VpcId": "vpc-838475fe", "HealthCheckProtocol": "HTTP", "HealthCheckPort": "traffic-port", "HealthCheckEnabled": true, "HealthCheckIntervalSeconds": 30, "HealthCheckTimeoutSeconds": 6, "HealthyThresholdCount": 5, "UnhealthyThresholdCount": 2, "HealthCheckPath": "/", "Matcher": { "HttpCode": "200-399" }, "TargetType": "alb", "IpAddressType": "ipv4" } ] }
有关更多信息,请参阅网络负载均衡器用户指南中的创建以 Application Load Balancer 作为目标的目标组。
示例 5:为 Gateway Load Balancer 创建目标组
以下
create-target-group
示例为 Gateway Load Balancer 创建目标组,其中目标为实例,目标组协议为GENEVE
。aws elbv2 create-target-group \ --name
my-glb-targetgroup
\ --protocolGENEVE
\ --port6081
\ --target-typeinstance
\ --vpc-idvpc-838475fe
输出:
{ "TargetGroups": [ { "TargetGroupArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-glb-targetgroup/00c3d57eacd6f40b6f", "TargetGroupName": "my-glb-targetgroup", "Protocol": "GENEVE", "Port": 6081, "VpcId": "vpc-838475fe", "HealthCheckProtocol": "TCP", "HealthCheckPort": "80", "HealthCheckEnabled": true, "HealthCheckIntervalSeconds": 10, "HealthCheckTimeoutSeconds": 5, "HealthyThresholdCount": 5, "UnhealthyThresholdCount": 2, "TargetType": "instance" } ] }
有关更多信息,请参阅 Gateway Load Balancer 用户指南中的创建目标组 < https://docs.aws.amazon.com/elasticloadbalancing/ latest/gateway/create-target-group.html>`__。
-
有关API详细信息,请参阅 “CreateTargetGroup AWS CLI
命令参考”。
-
- Java
-
- SDK适用于 Java 2.x
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 /* * Creates an Elastic Load Balancing target group. The target group specifies * how * the load balancer forward requests to instances in the group and how instance * health is checked. */ public String createTargetGroup(String protocol, int port, String vpcId, String targetGroupName) { CreateTargetGroupRequest targetGroupRequest = CreateTargetGroupRequest.builder() .healthCheckPath("/healthcheck") .healthCheckTimeoutSeconds(5) .port(port) .vpcId(vpcId) .name(targetGroupName) .protocol(protocol) .build(); CreateTargetGroupResponse targetGroupResponse = getLoadBalancerClient().createTargetGroup(targetGroupRequest); String targetGroupArn = targetGroupResponse.targetGroups().get(0).targetGroupArn(); String targetGroup = targetGroupResponse.targetGroups().get(0).targetGroupName(); System.out.println("The " + targetGroup + " was created with ARN" + targetGroupArn); return targetGroupArn; }
-
有关API详细信息,请参阅 “AWS SDK for Java 2.x API参考 CreateTargetGroup” 中的。
-
- JavaScript
-
- SDK对于 JavaScript (v3)
-
注意
还有更多相关信息 GitHub。查找完整示例,学习如何在 AWS 代码示例存储库
中进行设置和运行。 const client = new ElasticLoadBalancingV2Client({}); const { TargetGroups } = await client.send( new CreateTargetGroupCommand({ Name: NAMES.loadBalancerTargetGroupName, Protocol: "HTTP", Port: 80, HealthCheckPath: "/healthcheck", HealthCheckIntervalSeconds: 10, HealthCheckTimeoutSeconds: 5, HealthyThresholdCount: 2, UnhealthyThresholdCount: 2, VpcId: state.defaultVpc, }), );
-
有关API详细信息,请参阅 “AWS SDK for JavaScript API参考 CreateTargetGroup” 中的。
-
- PowerShell
-
- 用于 PowerShell
-
示例 1:此示例使用提供的参数创建新的目标组。
New-ELB2TargetGroup -HealthCheckEnabled 1 -HealthCheckIntervalSeconds 30 -HealthCheckPath '/index.html' -HealthCheckPort 80 -HealthCheckTimeoutSecond 5 -HealthyThresholdCount 2 -UnhealthyThresholdCount 5 -Port 80 -Protocol 'HTTP' -TargetType instance -VpcId 'vpc-2cfd7000' -Name 'NewTargetGroup'
输出:
HealthCheckEnabled : True HealthCheckIntervalSeconds : 30 HealthCheckPath : /index.html HealthCheckPort : 80 HealthCheckProtocol : HTTP HealthCheckTimeoutSeconds : 5 HealthyThresholdCount : 2 LoadBalancerArns : {} Matcher : Amazon.ElasticLoadBalancingV2.Model.Matcher Port : 80 Protocol : HTTP TargetGroupArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/NewTargetGroup/534e484681d801bf TargetGroupName : NewTargetGroup TargetType : instance UnhealthyThresholdCount : 5 VpcId : vpc-2cfd7000
-
有关API详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考CreateTargetGroup中的。
-
- 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_target_group( self, target_group_name: str, protocol: str, port: int, vpc_id: str ) -> Dict[str, Any]: """ Creates an Elastic Load Balancing target group. The target group specifies how the load balancer forwards requests to instances in the group and how instance health is checked. To speed up this demo, the health check is configured with shortened times and lower thresholds. In production, you might want to decrease the sensitivity of your health checks to avoid unwanted failures. :param target_group_name: The name of the target group to create. :param protocol: The protocol to use to forward requests, such as 'HTTP'. :param port: The port to use to forward requests, such as 80. :param vpc_id: The ID of the VPC in which the load balancer exists. :return: Data about the newly created target group. """ try: response = self.elb_client.create_target_group( Name=target_group_name, Protocol=protocol, Port=port, HealthCheckPath="/healthcheck", HealthCheckIntervalSeconds=10, HealthCheckTimeoutSeconds=5, HealthyThresholdCount=2, UnhealthyThresholdCount=2, VpcId=vpc_id, ) target_group = response["TargetGroups"][0] log.info(f"Created load balancing target group '{target_group_name}'.") return target_group except ClientError as err: log.error( f"Couldn't create load balancing target group '{target_group_name}'." ) error_code = err.response["Error"]["Code"] if error_code == "DuplicateTargetGroupName": log.error( f"Target group name {target_group_name} already exists. " "Check if the target group already exists." "Consider using a different name or deleting the existing target group if appropriate." ) elif error_code == "TooManyTargetGroups": log.error( "Too many target groups exist in the account. " "Consider deleting unused target groups to create space for new ones." ) log.error(f"Full error:\n\t{err}")
-
有关API详细信息,请参阅CreateTargetGroup中的 AWS SDKPython (Boto3) API 参考。
-