Cloud Control API ve Java SDK kullanarak kaynak yönetiminin tüm yaşam döngüsünü (oluşturma, okuma, güncelleme ve silme - CRUD) adım adım uygulayın. Bu eğitimde örnek olarak bir Virtual Private Cloud (VPC) kullanılmıştır ve eşzamansız görev işleme konusuna değinilmiştir.
Önkoşullar
Java SDK yüklenmiş ve yapılandırılmış olmalıdır.
Bir kaynağın özelliklerini ve yapısını tanımlayan kaynak meta verisi kavramına aşina olun. Daha fazla bilgi için bkz. Kaynak meta verisi.
Cloud Control API'nin genellikle eşzamansız işlemler kullandığını anlayın. Daha fazla bilgi için bkz. Eşzamanlı ve eşzamansız işlemler.
1. Adım: Kaynak türü meta verilerini alın
Bir kaynağı yönetmek için öncelikle meta verilerini alarak yapısını anlamanız gerekir. Meta verileri almak üzere GetResourceType işlemini çağırın. Aşağıdaki örnekte bir VPC için meta veriler alınmaktadır.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code, "VPC" in this example
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code, "VPC" in this example
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
// Configure runtime options.
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// Define the request path.
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resourceTypes/" + RESOURCE_TYPE_CODE;
com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders getResourceTypeHeaders = new com.aliyun.cloudcontrol20220830.models.GetResourceTypeHeaders()
.setXAcsAcceptLanguage("en-US"); // Select the language for the response. zh-CN: Chinese (default), en-US: English.
try {
// Send the request.
GetResourceTypeResponse getResourceTypeResponse = client.getResourceTypeWithOptions(requestPath, getResourceTypeHeaders, runtime);
// Print the response result.
System.out.println(new Gson().toJson(getResourceTypeResponse.getBody()));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Yanıt, VPC'nin özellikleri, yalnızca oluşturma sırasında belirtilen parametreler (createOnlyProperties), salt okunur özellikler (readOnlyProperties) ve her eylem için gereken izinler (handlers) dahil olmak üzere eksiksiz VPC meta verilerini döndürür. Bu bilgileri aşağıdaki adımlarda kullanacaksınız.
Örnek yanıt:
{
"requestId": "BE9E0796-DB31-5320-A446-1A2316E7CB92",
"resourceType": {
"createOnlyProperties": [
"/properties/DryRun",
"/properties/Ipv6Isp",
"/properties/EnableIpv6"
],
"deleteOnlyProperties": [],
"filterProperties": [
"/properties/DhcpOptionsSetId",
"/properties/ResourceGroupId",
"/properties/VpcId",
"/properties/VpcName",
"/properties/IsDefault"
],
"getOnlyProperties": [
"/properties/DryRun"
],
"getResponseProperties": [
"/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
"/properties/RegionId",
"/properties/VpcName",
"/properties/ResourceType",
"/properties/DhcpOptionsSetId",
"/properties/CreateTime",
"/properties/Tags/items/properties/TagKey",
"/properties/SecondaryCidrBlocks/items",
"/properties/Tags",
"/properties/IsDefault",
"/properties/UserCidrs/items",
"/properties/ResourceGroupId",
"/properties/CidrBlock",
"/properties/RouterId",
"/properties/Tags/items",
"/properties/Description",
"/properties/Ipv6CidrBlocks",
"/properties/SecondaryCidrBlocks",
"/properties/Status",
"/properties/VSwitchIds",
"/properties/Tags/items/properties/TagValue",
"/properties/Ipv6CidrBlocks/items",
"/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
"/properties/Ipv6CidrBlock",
"/properties/ClassicLinkEnabled",
"/properties/UserCidrs",
"/properties/VSwitchIds/items",
"/properties/VpcId"
],
"handlers": {
"create": {
"permissions": [
"vpc:CreateVpc"
]
},
"delete": {
"permissions": [
"vpc:DeleteVpc"
]
},
"get": {
"permissions": [
"vpc:ListTagResources",
"vpc:DescribeVpcAttribute",
"vpc:DescribeVpcs"
]
},
"list": {
"permissions": [
"vpc:DescribeVpcs"
]
},
"update": {
"permissions": [
"vpc:TagResources",
"vpc:AssociateVpcCidrBlock",
"vpc:MoveResourceGroup",
"vpc:ModifyVpcAttribute",
"vpc:UnTagResources",
"vpc:UnassociateVpcCidrBlock",
"vpc:EnableVpcClassicLink",
"vpc:DisableVpcClassicLink"
]
}
},
"info": {
"chargeType": "free",
"deliveryScope": "region",
"description": "A VPC instance represents a virtual private cloud that you created. You have full control over your VPC, such as specifying the IP address range, configuring route tables, and setting up gateways. You can use Alibaba Cloud resources such as Elastic Compute Service (ECS) instances, ApsaraDB RDS instances, and Server Load Balancer (SLB) instances within your VPC.",
"title": "Virtual Private Cloud"
},
"listOnlyProperties": [
"/properties/DryRun"
],
"listResponseProperties": [
"/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
"/properties/RegionId",
"/properties/VpcName",
"/properties/DhcpOptionsSetId",
"/properties/CreateTime",
"/properties/Tags/items/properties/TagKey",
"/properties/SecondaryCidrBlocks/items",
"/properties/Tags",
"/properties/IsDefault",
"/properties/UserCidrs/items",
"/properties/ResourceGroupId",
"/properties/CidrBlock",
"/properties/RouterId",
"/properties/Tags/items",
"/properties/Description",
"/properties/Ipv6CidrBlocks",
"/properties/SecondaryCidrBlocks",
"/properties/Status",
"/properties/VSwitchIds",
"/properties/Tags/items/properties/TagValue",
"/properties/Ipv6CidrBlocks/items",
"/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
"/properties/Ipv6CidrBlock",
"/properties/UserCidrs",
"/properties/VSwitchIds/items",
"/properties/VpcId"
],
"primaryIdentifier": "/properties/VpcId",
"product": "VPC",
"properties": {
"Status": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The status of the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The status of the VPC.",
"type": "string",
"updateType": false
},
"IsDefault": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "Indicates whether it is the default VPC.",
"readOnly": false,
"sensitive": false,
"title": "Indicates whether it is the default VPC.",
"type": "boolean",
"updateType": false
},
"Ipv6Isp": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The IPv6 CIDR block type for the VPC. Valid values:\n\n- **BGP** (default): Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, or **ChinaMobile** if you are on the single-line bandwidth whitelist.",
"operatePrivateType": [
"create"
],
"readOnly": false,
"sensitive": false,
"title": "The IPv6 CIDR block type for the VPC. Valid values:\n\n- **BGP** (default): Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, or **ChinaMobile** if you are on the single-line bandwidth whitelist.",
"type": "string",
"updateType": false
},
"Description": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The description of the VPC.",
"readOnly": false,
"sensitive": false,
"title": "The description of the VPC.",
"type": "string",
"updateType": true
},
"ResourceGroupId": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The ID of the resource group.",
"readOnly": false,
"sensitive": false,
"title": "The ID of the resource group.",
"type": "string",
"updateType": true
},
"ClassicLinkEnabled": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "The status of the ClassicLink feature.",
"readOnly": false,
"sensitive": false,
"title": "The status of the ClassicLink feature.",
"type": "boolean",
"updateType": true
},
"SecondaryCidrBlocks": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The secondary CIDR block information.",
"readOnly": false,
"sensitive": false,
"title": "The secondary CIDR block information.",
"type": "array",
"items": {
"description": "The secondary CIDR block of the VPC.",
"title": "The secondary CIDR block of the VPC.",
"type": "string",
"updateType": true
},
"updateType": true
},
"VSwitchIds": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "The list of VSwitches in the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The list of VSwitches in the VPC.",
"type": "array",
"items": {
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The list of VSwitches in the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The list of VSwitches in the VPC.",
"type": "string",
"updateType": false
},
"updateType": false
},
"CreateTime": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The time when the VPC was created.",
"readOnly": true,
"sensitive": false,
"title": "The time when the VPC was created.",
"type": "string",
"updateType": false
},
"DryRun": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "Indicates whether to perform a dry run. Valid values:\n- **true**: Sends a check request without creating the VPC. The system checks for required parameters, request format, and service limits. If the check fails, an error is returned. If the check passes, the `DryRunOperation` error code is returned.\n- **false** (default): Sends a normal request, and if the check passes, returns a 2xx HTTP status code and creates the VPC.",
"operatePrivateType": [
"create",
"list",
"get"
],
"readOnly": false,
"sensitive": false,
"title": "Indicates whether to perform a dry run. Valid values:\n- **true**: Sends a check request without creating the VPC. The system checks for required parameters, request format, and service limits. If the check fails, an error is returned. If the check passes, the `DryRunOperation` error code is returned.\n- **false** (default): Sends a normal request, and if the check passes, returns a 2xx HTTP status code and creates the VPC.",
"type": "boolean",
"updateType": false
},
"RouterId": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The router ID of the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The router ID of the VPC.",
"type": "string",
"updateType": false
},
"CidrBlock": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The private CIDR block of the VPC.",
"readOnly": false,
"sensitive": false,
"title": "The private CIDR block of the VPC.",
"type": "string",
"updateType": true
},
"UserCidrs": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
"readOnly": false,
"sensitive": false,
"title": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
"type": "array",
"items": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
"sensitive": false,
"title": "The CIDR block of the user-side network. To specify multiple CIDR blocks, separate them with commas. Up to 3 CIDR blocks are supported.",
"type": "string",
"updateType": false
},
"updateType": false
},
"EnableIpv6": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "Indicates whether to enable the IPv6 CIDR block. Valid values:\n\n- **false** (default): No.\n- **true**: Yes.",
"operatePrivateType": [
"create"
],
"readOnly": false,
"sensitive": false,
"title": "Indicates whether to enable the IPv6 CIDR block. Valid values:\n\n- **false** (default): No.\n- **true**: Yes.",
"type": "boolean",
"updateType": false
},
"DhcpOptionsSetId": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The ID of the DHCP options set.",
"readOnly": false,
"sensitive": false,
"title": "The ID of the DHCP options set.",
"type": "string",
"updateType": false
},
"VpcId": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The ID of the VPC.",
"readOnly": false,
"sensitive": false,
"title": "The ID of the VPC.",
"type": "string",
"updateType": false
},
"VpcName": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The name of the VPC.",
"readOnly": false,
"sensitive": false,
"title": "The name of the VPC.",
"type": "string",
"updateType": true
},
"RegionId": {
"isRequired": true,
"extMonitorInfo": false,
"description": "The region where the VPC is located.",
"readOnly": false,
"sensitive": false,
"title": "The region where the VPC is located.",
"type": "string",
"updateType": false
},
"Ipv6CidrBlocks": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"description": "The IPv6 CIDR block information of the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The IPv6 CIDR block information of the VPC.",
"type": "array",
"items": {
"extMonitorInfo": false,
"deprecated": false,
"description": "The IPv6 CIDR block information of the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The IPv6 CIDR block information of the VPC.",
"type": "object",
"properties": {
"Ipv6Isp": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The IPv6 CIDR block type of the VPC. Valid values:\n\n- **BGP**: Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, and **ChinaMobile** if you are on the single-line bandwidth whitelist.",
"readOnly": true,
"sensitive": false,
"title": "The IPv6 CIDR block type of the VPC. Valid values:\n\n- **BGP**: Alibaba Cloud BGP IPv6.\n- **ChinaMobile**: China Mobile (single line).\n- **ChinaUnicom**: China Unicom (single line).\n- **ChinaTelecom**: China Telecom (single line).\n\n\u003e This field can be set to **ChinaTelecom**, **ChinaUnicom**, and **ChinaMobile** if you are on the single-line bandwidth whitelist.",
"type": "string",
"updateType": false
},
"Ipv6CidrBlock": {
"isRequired": false,
"extMonitorInfo": false,
"deprecated": false,
"pattern": "",
"description": "The IPv6 CIDR block of the VPC.",
"readOnly": true,
"sensitive": false,
"title": "The IPv6 CIDR block of the VPC.",
"type": "string",
"updateType": false
}
},
"updateType": false
},
"updateType": false
},
"Ipv6CidrBlock": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The IPv6 address.",
"readOnly": false,
"sensitive": false,
"title": "The IPv6 address.",
"type": "string",
"updateType": true
},
"Tags": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The tags of the VPC.",
"readOnly": false,
"sensitive": false,
"title": "The tags of the VPC.",
"type": "array",
"items": {
"extMonitorInfo": false,
"deprecated": false,
"description": "The tags of the VPC.",
"sensitive": false,
"title": "The tags of the VPC.",
"type": "object",
"properties": {
"TagKey": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The key of the tag.",
"readOnly": false,
"sensitive": false,
"title": "The key of the tag.",
"type": "string",
"updateType": true
},
"TagValue": {
"isRequired": false,
"extMonitorInfo": false,
"description": "The value of the tag.",
"readOnly": false,
"sensitive": false,
"title": "The value of the tag.",
"type": "string",
"updateType": true
}
},
"updateType": false
},
"updateType": true
}
},
"publicProperties": [
"/properties/RouterId",
"/properties/VpcId",
"/properties/DhcpOptionsSetId",
"/properties/ResourceGroupId",
"/properties/UserCidrs",
"/properties/UserCidrs/items",
"/properties/VSwitchIds",
"/properties/RegionId",
"/properties/Ipv6CidrBlocks",
"/properties/VSwitchIds/items",
"/properties/Tags",
"/properties/Tags/items",
"/properties/Ipv6CidrBlocks/items",
"/properties/CidrBlock",
"/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
"/properties/Tags/items/properties/TagKey",
"/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
"/properties/Status",
"/properties/Tags/items/properties/TagValue",
"/properties/CreateTime",
"/properties/Ipv6CidrBlock",
"/properties/Description",
"/properties/VpcName",
"/properties/ClassicLinkEnabled",
"/properties/IsDefault",
"/properties/SecondaryCidrBlocks",
"/properties/SecondaryCidrBlocks/items"
],
"readOnlyProperties": [
"/properties/Ipv6CidrBlocks/items/properties/Ipv6Isp",
"/properties/CreateTime",
"/properties/RouterId",
"/properties/Ipv6CidrBlocks",
"/properties/Status",
"/properties/VSwitchIds",
"/properties/Ipv6CidrBlocks/items",
"/properties/Ipv6CidrBlocks/items/properties/Ipv6CidrBlock",
"/properties/VSwitchIds/items"
],
"required": [
"RegionId"
],
"resourceType": "VPC",
"sensitiveInfoProperties": [],
"updateOnlyProperties": [],
"updateTypeProperties": [
"/properties/ResourceGroupId",
"/properties/Tags",
"/properties/CidrBlock",
"/properties/Tags/items/properties/TagKey",
"/properties/Tags/items/properties/TagValue",
"/properties/Ipv6CidrBlock",
"/properties/Description",
"/properties/VpcName",
"/properties/ClassicLinkEnabled",
"/properties/SecondaryCidrBlocks",
"/properties/SecondaryCidrBlocks/items"
]
}
}
2. Adım: Bir kaynak oluşturun
Yeni bir kaynak oluşturmak için CreateResource işlemini kullanın. İstek gövdesi, kaynak meta verilerinde tanımlanan özellikleri içermelidir. Bu işlem eşzamansızdır ve ilerlemeyi izlemek için kullanacağınız bir taskId döndürür.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// The headers parameter allows you to customize request headers, override default values, or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap < > ();
// Request path.
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE;
java.util.Map < String, Object > body = TeaConverter.buildMap(
new TeaPair("IsDefault", true), // Specifies whether this is the default VPC.
new TeaPair("Description", "This is a test VPC"), // Description.
new TeaPair("VpcName", "VPC_Test"), // VPC name.
new TeaPair("Tags", java.util.Arrays.asList(
TeaConverter.buildMap(
new TeaPair("TagKey", "key"),
new TeaPair("TagValue", "value")
)
)), // VPC tags.
new TeaPair("EnableIpv6", false), // Specifies whether to enable the IPv6 CIDR block.
new TeaPair("DryRun", false) // Specifies whether to perform only a dry run.
);
// Configure request parameters.
com.aliyun.cloudcontrol20220830.models.CreateResourceRequest createResourceRequest = new com.aliyun.cloudcontrol20220830.models.CreateResourceRequest()
.setRegionId("cn-qingdao") // Region ID.
.setBody(body);
try {
// Initiate the request.
CreateResourceResponse createResourceResponse = client.createResourceWithOptions(requestPath, createResourceRequest, headers, runtime);
// Print the result.
System.out.println(new Gson().toJson(createResourceResponse.getBody()));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
3. Adım: Eşzamansız bir görevin durumunu kontrol edin
CreateResource veya DeleteResource gibi bir eşzamansız işlemi başlattıktan sonra, döndürülen taskId ile GetTask işlemini kullanarak durumunu kontrol edin.
Örnek yanıt:
{
"requestId": "D3AA2FD7-CA66-5A6D-B1AE-A5C8C785ADBB",
"resourceId": "vpc-m5eml8m3XXXXXXXX",
"resourcePath": "VPC/vpc-m5eml8m3XXXXXXXX",
"taskId": "task-5057a4fbef2bc1a4XXXXXXXX"
}
4. Adım: Bir kaynağı okuyun, güncelleyin ve silin
Bir kaynak oluşturduktan sonra, ayrıntılarını okumak, özelliklerini güncellemek veya silmek için resourceId değerini kullanabilirsiniz.
Tek bir kaynağı okuyun (GetResources)
Belirli bir kaynağın mevcut durumunu almak için istek yoluna resourceId değerini ekleyin.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com"; // Endpoint.
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// // Ignore SSL certificate verification.
// runtime.ignoreSSL = true;
// // Proxy configuration.
// runtime.httpProxy = "http://127.0.0.1:9898";
// runtime.httpsProxy = "http://user:password@127.0.0.1:8989";
// runtime.noProxy = "127.0.0.1,localhost";
// // Connection timeout.
// runtime.connectTimeout = 5000;
// // Read timeout.
// runtime.readTimeout = 10000;
// // Enable automatic retry.
// runtime.autoretry = true;
// // Set the maximum number of retries.
// runtime.maxAttempts = 3;
// The headers parameter allows you to customize request headers, override default values, or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap < > ();
String resourceId = "vrt-m5eyitbd6XXXXXXXX";
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE + "/" + resourceId;
// Request parameters.
com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
.setRegionId("cn-qingdao");
try {
// Initiate the request.
GetResourcesResponse getResourcesResponse = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
// Print the response.
System.out.println(new Gson().toJson(getResourcesResponse.getBody()));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Tüm kaynakları listeleyin (GetResources)
Bir bölgedeki belirli bir türdeki tüm kaynakları listelemek için temel kaynak yoluna bir istek gönderin. Filtreler de uygulayabilirsiniz.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// The headers parameter allows you to customize request headers, override default values, or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap < > ();
// headers.put("x-acs-action", "GetResource"); // Set the API operation name.
// Request path.
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE;
// Filter conditions (optional).
// java.util.Map < String, Object > filter = TeaConverter.buildMap(
// new TeaPair("IsDefault", true), // Specifies whether this is the default VPC.
// new TeaPair("ResourceGroupId", "<YOUR_RESOURCEGROUPID>"), // Resource group ID.
// new TeaPair("DhcpOptionsSetId", "<YOUR_DHCPOPTIONSSETID>"), // DHCP options set ID.
// new TeaPair("VpcId", "<YOUR_VPCID>"), // VPC ID.
// new TeaPair("VpcName", "<YOUR_VPCNAME>") // VPC name.
// );
com.aliyun.cloudcontrol20220830.models.GetResourcesRequest getResourcesRequest = new com.aliyun.cloudcontrol20220830.models.GetResourcesRequest()
// .setFilter(filter)
.setRegionId("cn-qingdao");
try {
GetResourcesResponse getResourcesResponse = client.getResourcesWithOptions(requestPath, getResourcesRequest, headers, runtime);
System.out.println(new Gson().toJson(getResourcesResponse.getBody()));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Bir kaynağı güncelleyin (UpdateResource)
Yolda resourceId değerini ve istek gövdesinde güncellenecek özellikleri belirtin.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// The headers parameter allows you to customize request headers, override default values, or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap < > ();
// Resource ID.
String resourceId = "vpc-m5eml8m3XXXXXXXX";
// Request path.
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE +"/" + resourceId;
java.util.Map < String, Object > body = TeaConverter.buildMap(
new TeaPair("Description", "Updated test VPC description"), // Update the resource description.
new TeaPair("VpcName", "UpdateVpc"), // Update the resource name.
new TeaPair("Tags", java.util.Arrays.asList(
TeaConverter.buildMap(
new TeaPair("TagKey", "key1"),
new TeaPair("TagValue", "value1")
)
)) // Update the resource tags.
);
com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest updateResourceRequest = new com.aliyun.cloudcontrol20220830.models.UpdateResourceRequest()
.setRegionId("cn-qingdao") // Region.
.setBody(body);
try {
// Initiate the request.
UpdateResourceResponse updateResourceResponse = client.updateResourceWithOptions(requestPath, updateResourceRequest, headers, runtime);
System.out.println(new Gson().toJson(updateResourceResponse.getBody()) + new Gson().toJson(updateResourceResponse.statusCode));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
Bir kaynağı silin (DeleteResource)
İstek yolunda resourceId değerini belirtin. Oluşturma işlemi gibi, silme işlemi de eşzamansızdır ve izleme amacıyla bir taskId döndürür.
Silme işlemi geri alınamaz. Dikkatli Proceed.
import com.aliyun.cloudcontrol20220830.Client;
import com.aliyun.cloudcontrol20220830.models.*;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaException;
import com.aliyun.tea.TeaPair;
import com.google.gson.Gson;
public class Sample {
private static final String PRODUCT_CODE = "VPC"; // Product code. In this example, "VPC".
private static final String RESOURCE_TYPE_CODE = "VPC"; // Resource type code. In this example, "VPC".
public static void main(String[] args) throws Exception {
// Initialize the client.
com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
.setAccessKeyId(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"))
.setAccessKeySecret(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
config.endpoint = "cloudcontrol.aliyuncs.com";
com.aliyun.cloudcontrol20220830.Client client = new com.aliyun.cloudcontrol20220830.Client(config);
com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
// The headers parameter allows you to customize request headers, override default values, or add extra information.
java.util.Map < String, String > headers = new java.util.HashMap < > ();
// Resource ID.
String resourceId = "vpc-m5ei5XXXXXXXX";
// Request path.
String requestPath = "/api/v1/providers/Aliyun/products/" + PRODUCT_CODE + "/resources/" + RESOURCE_TYPE_CODE + "/" + resourceId;
// Request parameters.
com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest deleteResourceRequest = new com.aliyun.cloudcontrol20220830.models.DeleteResourceRequest()
.setRegionId("cn-qingdao");
try {
// Initiate the request.
DeleteResourceResponse deleteResourceResponse = client.deleteResourceWithOptions(requestPath, deleteResourceRequest, headers, runtime);
// Print the result.
System.out.println(new Gson().toJson(deleteResourceResponse.getBody()));
} catch (TeaException error) {
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// Error message.
System.out.println(error.getMessage());
// Diagnostic address.
System.out.println(error.getData().get("Recommend"));
com.aliyun.teautil.Common.assertAsString(error.message);
}
}
}
SSS
Hata: Cannot invoke "com.aliyun.credentials.Client.getCredential()" because "this._credential" is null
Bu hata, SDK'nın Alibaba Cloud kimlik bilgilerinizi (AccessKey çifti) bulamadığını gösterir.
Çözüm:
-
Ortam değişkenlerinizi doğrulayın. Kimlik bilgilerini sağlamanın önerilen yolu,
ALIBABA_CLOUD_ACCESS_KEY_IDveALIBABA_CLOUD_ACCESS_KEY_SECRETortam değişkenlerini ayarlamaktır. Kodunuzu çalıştırdığınız terminalde veya çalıştırma yapılandırmasında bunların doğru şekilde ayarlandığından emin olun.Ortam değişkenlerinizi doğrulamak için işletim sisteminize uygun komutu çalıştırın:
Linux/macOS
echo $ALIBABA_CLOUD_ACCESS_KEY_ID echo $ALIBABA_CLOUD_ACCESS_KEY_SECRETWindows
echo %ALIBABA_CLOUD_ACCESS_KEY_ID% echo %ALIBABA_CLOUD_ACCESS_KEY_SECRET%Başarılı bir yapılandırmada AccessKey ID'niz yazdırılır. Çıktı boşsa, değişken doğru ayarlanmamış demektir ve yeniden yapılandırmanız gerekir.
Daha fazla bilgi için bkz. Linux, macOS ve Windows'da ortam değişkenlerini yapılandırma.
-
Başlatma kodunuzu kontrol edin. İstemci başlatma kodunuzun ortam değişkenlerini doğru şekilde okuduğundan veya geçerli bir kimlik bilgisi sağlayıcısı ile yapılandırıldığından emin olun.
ÖnemliAccessKey çiftinizi doğrudan kaynak kodunuzda sabit kodlamayın; bu, önemli bir güvenlik riskidir.