更新时间:2024-05-17 GMT+08:00

创建缓存实例

功能介绍

创建缓存实例,该接口创建的缓存实例支持按需计费。

调用方法

请参见如何调用API

URI

POST /v2/{project_id}/instances

表1 路径参数

参数

是否必选

参数类型

描述

project_id

String

项目ID。获取方法请参见获取项目ID

请求参数

表2 请求Body参数

参数

是否必选

参数类型

描述

name

String

实例名称。

由英文字符、中文或数字开头,只能由英文字母、数字、中划线和下划线组成。

创建单个实例时,名称长度为4到64位的字符串。批量创建实例时,名称长度为4到56位的字符串,且实例名称格式为“自定义名称-n”,其中n从000开始,依次递增。例如,批量创建两个实例,自定义名称为dcs_demo,则两个实例的名称为dcs_demo-000和dcs_demo-001。

engine

String

缓存引擎:Redis和Memcached。

engine_version

String

缓存版本。

当缓存引擎为Redis时,该字段为必选,取值为3.0、4.0、5.0、6.0。

当缓存引擎为Memcached时,该字段为可选,取值为空。

capacity

Float

缓存容量(G Byte)

  • Redis3.0:单机和主备类型实例取值:2、4、8、16、32、64。Proxy集群实例规格支持64、128、256、512和1024。

  • Redis4.0和Redis5.0、Redis 6.0:单机和主备类型实例取值:0.125、0.25、0.5、1、2、4、8、16、32、64。集群实例规格取值:4、8、16、24、32、48、64、96、128、192、256、384、512、768、1024。Redis4.0/5.0读写分离实例取值:8、16、32、64。

  • Memcached:单机和主备类型实例取值:2、4、8、16、32、64。

spec_code

String

产品规格编码。具体查询方法如下:

  • 方法一:登录分布式缓存的控制台界面创建缓存实例页面,查找对应的实例规格名称。

  • 方法二:调用查询产品规格接口查询。

az_codes

Array of strings

创建缓存节点到指定且有资源的可用区Code。具体查询方法,请参考查询可用区信息接口,在查询时,请注意查看该可用区是否有资源。

如果是创建主备、读写分离、Proxy集群、Cluster集群实例,支持跨可用区部署,可以为备节点指定备可用区。在为节点指定可用区时,用逗号分隔开,具体请查看示例。

vpc_id

String

虚拟私有云ID。

获取方法如下:

  • 方法1:登录虚拟私有云服务的控制台界面,在我的VPC页面查找VPC ID。

  • 方法2:通过虚拟私有云服务的API接口查询,具体操作可参考查询VPC列表

subnet_id

String

子网的网络ID。

获取方法如下:

  • 方法1:登录虚拟私有云服务的控制台界面,单击VPC下的子网,进入子网页面,查找网络ID。

  • 方法2:通过虚拟私有云服务的API接口查询,具体操作可参考查询子网列表

security_group_id

String

指定实例所属的安全组。

当engine为Memcached时,该参数为必选。Memcached实例支持安全组访问控制。

当engine为Redis且engine_version为4.0、5.0和6.0时,该参数为可选。Redis4.0及以上版本的基础版实例不支持安全组控制访问,只支持白名单控制。

获取方法如下:

  • 方法1:登录虚拟私有云服务的控制台界面,在安全组的详情页面查找安全组ID。

  • 方法2:通过虚拟私有云服务的API接口查询,具体操作可参考查询安全组列表

publicip_id

String

Redis缓存实例绑定的弹性IP地址的id。

如果开启了公网访问功能(即enable_publicip为true),该字段为必选。

缺省值:false

enterprise_project_id

String

企业项目ID。

enterprise_project_name

String

企业项目名称。

description

String

实例的描述信息。

长度不超过1024的字符串。

说明:

\与"在json报文中属于特殊字符,如果参数值中需要显示\或者"字符,请在字符前增加转义字符\,比如\\或者\"。

enable_ssl

Boolean

Redis缓存实例开启公网访问功能时,是否选择支持ssl。目前仅Redis 3.0支持配置该参数。

  • true:开启

  • false:不开启

private_ip

String

创建缓存实例手动指定的IP地址,支持Redis和Memcached。

instance_num

Integer

表示批量创建缓存实例时,创建的实例个数。仅Redis和Memcached实例支持批量创建。

默认值:1

取值范围:1-100

缺省值:1

maintain_begin

String

维护时间窗开始时间,为UTC时间,格式为HH:mm:ss

  • 维护时间窗开始和结束时间必须为指定的时间段,可参考查询维护时间窗时间段获取。

  • 开始时间必须为18:00:00、19:00:00等整点时间。

  • 该参数不能单独为空,若该值为空,则结束时间也为空。系统分配一个默认开始时间18:00:00。

maintain_end

String

维护时间窗结束时间,为UTC时间,格式为HH:mm:ss。

  • 维护时间窗开始和结束时间必须为指定的时间段,可参考查询维护时间窗时间段获取。

  • 结束时间在开始时间基础上加一个小时,即当开始时间为18:00:00时,结束时间为19:00:00。

  • 该参数不能单独为空,若该值为空,则开始时间也为空,系统分配一个默认结束时间19:00:00。

password

String

缓存实例的认证信息

说明:

当“no_password_access”配置为“false”或未配置时,请求消息中须包含password参数。 Redis类型的缓存实例密码复杂度要求:

  • 输入长度为8到64位的字符串。

  • 新密码不能与旧密码相同。

  • 必须包含如下四种字符中的三种组合:

    • 小写字母

    • 大写字母

    • 数字

    • 特殊字符包括(`~!@#$^&*()-_=+\|{},<.>/?)

no_password_access

Boolean

是否允许免密码访问缓存实例。

  • true:该实例无需密码即可访问。

  • false:该实例必须通过密码认证才能访问。 若未配置该参数则默认值为“false”。

缺省值:false

bss_param

BssParam object

表示计费模式的相关参数。如果为空,则默认计费模式为按需计费;暂不支持其他计费方式。

instance_backup_policy

BackupPolicy object

备份策略,实例类型为主备和集群时支持。

tags

Array of ResourceTag objects

实例标签键值。

access_user

String

当缓存类型为Redis时,不需要设置,保持为空即可。

当缓存引擎为Memcached,且“no_password_access”为“false”时才需要设置,表示通过密码认证访问缓存实例的认证用户名。

由英文字符开头,只能由英文字母、数字、中划线和下划线组成,长度为1~64的字符。

  • 当缓存引擎为Memcached时,该参数为可选项。

enable_publicip

Boolean

Redis 3.0缓存实例是否开启公网访问功能。

  • true:开启

  • false:不开启

缺省值:false

port

Integer

实例自定义端口。只有创建Redis 4.0以上版本的实例才支持自定义端口,Redis 3.0和Memcached实例不支持。

创建Redis4.0、Redis5.0、Redis6.0实例,如果没发送该参数或该参数为空,表示实例使用默认端口6379。如果自定义端口,端口范围为1~65535的任意数字。

rename_commands

Object

支持自定义重命名高危命令。

创建Redis4.0、Redis5.0、Redis6.0实例,如果没发送该参数或该参数为空,表示没有需要重命名的命令。当前支持重命名的高危命令有command、keys、flushdb、flushall、scan、hscan、sscan、zscan和hgetall,其他命令暂不支持重命名。

template_id

String

参数模板ID。

表3 BssParam

参数

是否必选

参数类型

描述

is_auto_renew

String

当选择包年包月时,该字段为必选,表示是否自动续订资源。 取值范围:

  • false:不自动续订;

  • true:自动续订; 默认值为:false 约束: 如果设置为自动续订,到期后,会自动续订一个月(自动续订时间后续可能会变化),详情可联系客服咨询。

缺省值:false

charging_mode

String

付费方式。默认值是postPaid,即按需付费。

缺省值:postPaid

is_auto_pay

String

功能说明:下单订购后,是否自动从客户的账户中支付;默认是“不自动支付” 。

取值范围:

  • true:是(自动支付,从账户余额自动扣费)

  • false:否(默认值,只提交订单不支付,需要客户手动去支付)

约束: 自动支付时,只能使用账户的现金支付;如果要使用代金券,请选择不自动支付,然后在用户费用中心,选择代金券支付。

如果没有设置成自动支付,即设置为false时,在创建实例之后,实例状态为“支付中”,用户必须在“费用中心 > 我的订单”,完成订单支付,否则订单一直在支付中,实例没有创建成功

period_type

String

当选择包年包月时,该字段为必选,表示订购资源的周期类型。

取值范围如下:

  • month:表示包月

  • year:表示包年

period_num

Integer

功能说明:订购周期数 当选择按需时,该字段非必选。 取值范围:后续会随运营策略变化

  • period_type为month时,为1到9

  • period_type为year时,为1到3

约束:同period_type约束。

表4 BackupPolicy

参数

是否必选

参数类型

描述

backup_type

String

备份类型。

  • auto:自动备份

  • manual:手动备份

save_days

Integer

当backup_type设置为auto时,该参数为必填。 保留天数,单位:天,取值范围:1-7。

periodical_backup_plan

BackupPlan object

备份计划,当backup_type设置为auto时,该参数为必填。

表5 BackupPlan

参数

是否必选

参数类型

描述

timezone_offset

String

备份的时区。取值为-1200 ~+1200之间的时区。若为空则默认使用DCS-Server节点的当前时区。

backup_at

Array of integers

每周的周几开始备份,取值1-7,1代表周一,7代表周日。

period_type

String

备份周期类型,目前支持“weekly”。

begin_at

String

备份执行时间,“00:00-01:00”代表0点开始执行备份。只能是整点时间段,间隔时间限定为一个小时。

表6 ResourceTag

参数

是否必选

参数类型

描述

key

String

标签键

  • 不能为空。

  • 对于同一资源键值唯一。

  • 长度不超过36个字符。

  • 标签的键必须唯一且输入不能为空。

value

String

标签值

  • action为create时必选。action为delete时非必选。

  • 长度不超过43个字符。

响应参数

状态码: 200

表7 响应Body参数

参数

参数类型

描述

instances

Array of Instances objects

缓存实例ID和名称,如果批量创建实例,则会返回多个。

表8 Instances

参数

参数类型

描述

instance_id

String

缓存实例ID。

instance_name

String

缓存实例名称。

状态码: 400

表9 响应Body参数

参数

参数类型

描述

error_msg

String

错误信息

最大长度:1024

error_code

String

错误码

最大长度:9

error_ext_msg

String

扩展错误信息(暂未使用,赋值为null)

最大长度:1024

状态码: 401

表10 响应Body参数

参数

参数类型

描述

error_msg

String

错误信息

最大长度:1024

error_code

String

错误码

最大长度:9

error_ext_msg

String

扩展错误信息(暂未使用,赋值为null)

最大长度:1024

状态码: 403

表11 响应Body参数

参数

参数类型

描述

error_msg

String

错误信息

最大长度:1024

error_code

String

错误码

最大长度:9

error_ext_msg

String

扩展错误信息(暂未使用,赋值为null)

最大长度:1024

状态码: 404

表12 响应Body参数

参数

参数类型

描述

error_msg

String

错误信息

最大长度:1024

error_code

String

错误码

最大长度:9

error_ext_msg

String

扩展错误信息(暂未使用,赋值为null)

最大长度:1024

状态码: 500

表13 响应Body参数

参数

参数类型

描述

error_msg

String

错误信息

最大长度:1024

error_code

String

错误码

最大长度:9

error_ext_msg

String

扩展错误信息(暂未使用,赋值为null)

最大长度:1024

请求示例

  • 创建Redis实例

    POST https://{dcs_endpoint}/v2/{project_id}/instances
    
    {
      "name" : "dcs-APITest",
      "description" : "Test",
      "engine" : "Redis",
      "engine_version" : "5.0",
      "enterprise_project_id" : 0,
      "enterprise_project_name" : "default",
      "vpc_id" : "5e37b3be-950a-48e1-b498-65b63d336481",
      "security_group_id" : "securityGroupId",
      "enable_ssl" : false,
      "private_ip" : "",
      "az_codes" : [ "region01" ],
      "capacity" : 1,
      "access_user" : "",
      "password" : "********",
      "enable_publicip" : false,
      "spec_code" : "redis.single.xu1.large.1",
      "subnet_id" : "a4112635-3ec0-471c-95c3-5cf49b9533af",
      "no_password_access" : false,
      "template_id" : "b3ecc9c7-1133-4c47-a06a-21366e227d61"
    }
  • 创建按需的Redis主备实例(设置了自定义端口、重命名高危命令、跨可用区部署)

    {
      "enterprise_project_name" : "default",
      "vpc_id" : "c5cd009b-9ba9-41f2-9a26-2b8c3f3ffd39",
      "description" : "Test",
      "security_group_id" : "d57fad27-e3e9-43b7-9498-0a698ab63b27",
      "port" : 4040,
      "enable_ssl" : false,
      "private_ip" : "",
      "az_codes" : [ "region01", "region02" ],
      "capacity" : 2,
      "access_user" : "",
      "instance_num" : 1,
      "enterprise_project_id" : 0,
      "password" : "********",
      "enable_publicip" : false,
      "engine" : "Redis",
      "spec_code" : "redis.ha.au1.large.2",
      "name" : "dcs-demo",
      "subnet_id" : "7e95c4d6-d7af-424c-a3cf-2be10968fe81",
      "engine_version" : "4.0",
      "no_password_access" : false,
      "rename_commands" : {
        "keys" : "keys001",
        "flushdb" : "flushdb001",
        "flushall" : "flushall001"
      }
    }

响应示例

状态码: 200

下发创建缓存实例任务成功。

查看实例状态为RUNNING时,即缓存实例创建成功。

  • 示例 1

    {
      "instances" : [ {
        "instance_id" : "3c49fd6b-fc7c-419e-9644-b6cce008653f",
        "instance_name" : "dcs-test005"
      } ]
    }
  • 示例 2

    {
      "instances" : [ {
        "instance_id" : "77284d69-cd51-4bf1-aa30-2e60f055800c",
        "instance_name" : "dcs-APITest1"
      } ]
    }

状态码: 400

非法请求。

{
  "error_code" : "DCS.1004",
  "error_msg" : "Project ID does not match the token."
}

状态码: 401

认证信息非法。

{
  "error_code" : "DCS.1001",
  "error_msg" : "Invalid token."
}

状态码: 403

请求被拒绝访问。

{
  "error_code" : "DCS.2003",
  "error_msg" : "This role does not have the permission to perform this operation."
}

状态码: 404

所请求的资源不存在。

{
  "error_code" : "DCS.4001",
  "error_msg" : "The requested URL does not exist."
}

状态码: 500

内部服务错误

{
  "error_code" : "DCS.5000",
  "error_msg" : "Internal service error."
}

SDK代码示例

SDK代码示例如下。

  • 创建Redis实例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.dcs.v2.region.DcsRegion;
    import com.huaweicloud.sdk.dcs.v2.*;
    import com.huaweicloud.sdk.dcs.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class CreateInstanceSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withAk(ak)
                    .withSk(sk);
    
            DcsClient client = DcsClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(DcsRegion.valueOf("<YOUR REGION>"))
                    .build();
            CreateInstanceRequest request = new CreateInstanceRequest();
            CreateInstanceBody body = new CreateInstanceBody();
            List<String> listbodyAzCodes = new ArrayList<>();
            listbodyAzCodes.add("region01");
            body.withTemplateId("b3ecc9c7-1133-4c47-a06a-21366e227d61");
            body.withEnablePublicip(false);
            body.withAccessUser("");
            body.withNoPasswordAccess(false);
            body.withPassword("********");
            body.withPrivateIp("");
            body.withEnableSsl(false);
            body.withDescription("Test");
            body.withEnterpriseProjectName("default");
            body.withEnterpriseProjectId("0");
            body.withSecurityGroupId("securityGroupId");
            body.withSubnetId("a4112635-3ec0-471c-95c3-5cf49b9533af");
            body.withVpcId("5e37b3be-950a-48e1-b498-65b63d336481");
            body.withAzCodes(listbodyAzCodes);
            body.withSpecCode("redis.single.xu1.large.1");
            body.withCapacity(1f);
            body.withEngineVersion("5.0");
            body.withEngine("Redis");
            body.withName("dcs-APITest");
            request.withBody(body);
            try {
                CreateInstanceResponse response = client.createInstance(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • 创建按需的Redis主备实例(设置了自定义端口、重命名高危命令、跨可用区部署)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    package com.huaweicloud.sdk.test;
    
    import com.huaweicloud.sdk.core.auth.ICredential;
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    import com.huaweicloud.sdk.core.exception.ConnectionException;
    import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
    import com.huaweicloud.sdk.core.exception.ServiceResponseException;
    import com.huaweicloud.sdk.dcs.v2.region.DcsRegion;
    import com.huaweicloud.sdk.dcs.v2.*;
    import com.huaweicloud.sdk.dcs.v2.model.*;
    
    import java.util.List;
    import java.util.ArrayList;
    
    public class CreateInstanceSolution {
    
        public static void main(String[] args) {
            // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
            // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
            String ak = System.getenv("CLOUD_SDK_AK");
            String sk = System.getenv("CLOUD_SDK_SK");
    
            ICredential auth = new BasicCredentials()
                    .withAk(ak)
                    .withSk(sk);
    
            DcsClient client = DcsClient.newBuilder()
                    .withCredential(auth)
                    .withRegion(DcsRegion.valueOf("<YOUR REGION>"))
                    .build();
            CreateInstanceRequest request = new CreateInstanceRequest();
            CreateInstanceBody body = new CreateInstanceBody();
            List<String> listbodyAzCodes = new ArrayList<>();
            listbodyAzCodes.add("region01");
            listbodyAzCodes.add("region02");
            body.withRenameCommands("{\"keys\":\"keys001\",\"flushall\":\"flushall001\",\"flushdb\":\"flushdb001\"}");
            body.withPort(4040);
            body.withEnablePublicip(false);
            body.withAccessUser("");
            body.withNoPasswordAccess(false);
            body.withPassword("********");
            body.withInstanceNum(1);
            body.withPrivateIp("");
            body.withEnableSsl(false);
            body.withDescription("Test");
            body.withEnterpriseProjectName("default");
            body.withEnterpriseProjectId("0");
            body.withSecurityGroupId("d57fad27-e3e9-43b7-9498-0a698ab63b27");
            body.withSubnetId("7e95c4d6-d7af-424c-a3cf-2be10968fe81");
            body.withVpcId("c5cd009b-9ba9-41f2-9a26-2b8c3f3ffd39");
            body.withAzCodes(listbodyAzCodes);
            body.withSpecCode("redis.ha.au1.large.2");
            body.withCapacity(2f);
            body.withEngineVersion("4.0");
            body.withEngine("Redis");
            body.withName("dcs-demo");
            request.withBody(body);
            try {
                CreateInstanceResponse response = client.createInstance(request);
                System.out.println(response.toString());
            } catch (ConnectionException e) {
                e.printStackTrace();
            } catch (RequestTimeoutException e) {
                e.printStackTrace();
            } catch (ServiceResponseException e) {
                e.printStackTrace();
                System.out.println(e.getHttpStatusCode());
                System.out.println(e.getRequestId());
                System.out.println(e.getErrorCode());
                System.out.println(e.getErrorMsg());
            }
        }
    }
    
  • 创建Redis实例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkdcs.v2.region.dcs_region import DcsRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkdcs.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = __import__('os').getenv("CLOUD_SDK_AK")
        sk = __import__('os').getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
    
        client = DcsClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(DcsRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = CreateInstanceRequest()
            listAzCodesbody = [
                "region01"
            ]
            request.body = CreateInstanceBody(
                template_id="b3ecc9c7-1133-4c47-a06a-21366e227d61",
                enable_publicip=False,
                access_user="",
                no_password_access=False,
                password="********",
                private_ip="",
                enable_ssl=False,
                description="Test",
                enterprise_project_name="default",
                enterprise_project_id="0",
                security_group_id="securityGroupId",
                subnet_id="a4112635-3ec0-471c-95c3-5cf49b9533af",
                vpc_id="5e37b3be-950a-48e1-b498-65b63d336481",
                az_codes=listAzCodesbody,
                spec_code="redis.single.xu1.large.1",
                capacity=1,
                engine_version="5.0",
                engine="Redis",
                name="dcs-APITest"
            )
            response = client.create_instance(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 创建按需的Redis主备实例(设置了自定义端口、重命名高危命令、跨可用区部署)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    # coding: utf-8
    
    from huaweicloudsdkcore.auth.credentials import BasicCredentials
    from huaweicloudsdkdcs.v2.region.dcs_region import DcsRegion
    from huaweicloudsdkcore.exceptions import exceptions
    from huaweicloudsdkdcs.v2 import *
    
    if __name__ == "__main__":
        # The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        # In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak = __import__('os').getenv("CLOUD_SDK_AK")
        sk = __import__('os').getenv("CLOUD_SDK_SK")
    
        credentials = BasicCredentials(ak, sk) \
    
        client = DcsClient.new_builder() \
            .with_credentials(credentials) \
            .with_region(DcsRegion.value_of("<YOUR REGION>")) \
            .build()
    
        try:
            request = CreateInstanceRequest()
            listAzCodesbody = [
                "region01",
                "region02"
            ]
            request.body = CreateInstanceBody(
                rename_commands="{\"keys\":\"keys001\",\"flushall\":\"flushall001\",\"flushdb\":\"flushdb001\"}",
                port=4040,
                enable_publicip=False,
                access_user="",
                no_password_access=False,
                password="********",
                instance_num=1,
                private_ip="",
                enable_ssl=False,
                description="Test",
                enterprise_project_name="default",
                enterprise_project_id="0",
                security_group_id="d57fad27-e3e9-43b7-9498-0a698ab63b27",
                subnet_id="7e95c4d6-d7af-424c-a3cf-2be10968fe81",
                vpc_id="c5cd009b-9ba9-41f2-9a26-2b8c3f3ffd39",
                az_codes=listAzCodesbody,
                spec_code="redis.ha.au1.large.2",
                capacity=2,
                engine_version="4.0",
                engine="Redis",
                name="dcs-demo"
            )
            response = client.create_instance(request)
            print(response)
        except exceptions.ClientRequestException as e:
            print(e.status_code)
            print(e.request_id)
            print(e.error_code)
            print(e.error_msg)
    
  • 创建Redis实例

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        dcs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            Build()
    
        client := dcs.NewDcsClient(
            dcs.DcsClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.CreateInstanceRequest{}
    	var listAzCodesbody = []string{
            "region01",
        }
    	templateIdCreateInstanceBody:= "b3ecc9c7-1133-4c47-a06a-21366e227d61"
    	enablePublicipCreateInstanceBody:= false
    	accessUserCreateInstanceBody:= ""
    	noPasswordAccessCreateInstanceBody:= false
    	passwordCreateInstanceBody:= "********"
    	privateIpCreateInstanceBody:= ""
    	enableSslCreateInstanceBody:= false
    	descriptionCreateInstanceBody:= "Test"
    	enterpriseProjectNameCreateInstanceBody:= "default"
    	enterpriseProjectIdCreateInstanceBody:= "0"
    	securityGroupIdCreateInstanceBody:= "securityGroupId"
    	engineVersionCreateInstanceBody:= "5.0"
    	request.Body = &model.CreateInstanceBody{
    		TemplateId: &templateIdCreateInstanceBody,
    		EnablePublicip: &enablePublicipCreateInstanceBody,
    		AccessUser: &accessUserCreateInstanceBody,
    		NoPasswordAccess: &noPasswordAccessCreateInstanceBody,
    		Password: &passwordCreateInstanceBody,
    		PrivateIp: &privateIpCreateInstanceBody,
    		EnableSsl: &enableSslCreateInstanceBody,
    		Description: &descriptionCreateInstanceBody,
    		EnterpriseProjectName: &enterpriseProjectNameCreateInstanceBody,
    		EnterpriseProjectId: &enterpriseProjectIdCreateInstanceBody,
    		SecurityGroupId: &securityGroupIdCreateInstanceBody,
    		SubnetId: "a4112635-3ec0-471c-95c3-5cf49b9533af",
    		VpcId: "5e37b3be-950a-48e1-b498-65b63d336481",
    		AzCodes: listAzCodesbody,
    		SpecCode: "redis.single.xu1.large.1",
    		Capacity: float32(1),
    		EngineVersion: &engineVersionCreateInstanceBody,
    		Engine: "Redis",
    		Name: "dcs-APITest",
    	}
    	response, err := client.CreateInstance(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    
  • 创建按需的Redis主备实例(设置了自定义端口、重命名高危命令、跨可用区部署)

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    package main
    
    import (
    	"fmt"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
        dcs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2"
    	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2/model"
        region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2/region"
    )
    
    func main() {
        // The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
        // In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
        ak := os.Getenv("CLOUD_SDK_AK")
        sk := os.Getenv("CLOUD_SDK_SK")
    
        auth := basic.NewCredentialsBuilder().
            WithAk(ak).
            WithSk(sk).
            Build()
    
        client := dcs.NewDcsClient(
            dcs.DcsClientBuilder().
                WithRegion(region.ValueOf("<YOUR REGION>")).
                WithCredential(auth).
                Build())
    
        request := &model.CreateInstanceRequest{}
    	var listAzCodesbody = []string{
            "region01",
    	    "region02",
        }
    	var renameCommandsCreateInstanceBody interface{} = "{\"keys\":\"keys001\",\"flushall\":\"flushall001\",\"flushdb\":\"flushdb001\"}"
    	portCreateInstanceBody:= int32(4040)
    	enablePublicipCreateInstanceBody:= false
    	accessUserCreateInstanceBody:= ""
    	noPasswordAccessCreateInstanceBody:= false
    	passwordCreateInstanceBody:= "********"
    	instanceNumCreateInstanceBody:= int32(1)
    	privateIpCreateInstanceBody:= ""
    	enableSslCreateInstanceBody:= false
    	descriptionCreateInstanceBody:= "Test"
    	enterpriseProjectNameCreateInstanceBody:= "default"
    	enterpriseProjectIdCreateInstanceBody:= "0"
    	securityGroupIdCreateInstanceBody:= "d57fad27-e3e9-43b7-9498-0a698ab63b27"
    	engineVersionCreateInstanceBody:= "4.0"
    	request.Body = &model.CreateInstanceBody{
    		RenameCommands: &renameCommandsCreateInstanceBody,
    		Port: &portCreateInstanceBody,
    		EnablePublicip: &enablePublicipCreateInstanceBody,
    		AccessUser: &accessUserCreateInstanceBody,
    		NoPasswordAccess: &noPasswordAccessCreateInstanceBody,
    		Password: &passwordCreateInstanceBody,
    		InstanceNum: &instanceNumCreateInstanceBody,
    		PrivateIp: &privateIpCreateInstanceBody,
    		EnableSsl: &enableSslCreateInstanceBody,
    		Description: &descriptionCreateInstanceBody,
    		EnterpriseProjectName: &enterpriseProjectNameCreateInstanceBody,
    		EnterpriseProjectId: &enterpriseProjectIdCreateInstanceBody,
    		SecurityGroupId: &securityGroupIdCreateInstanceBody,
    		SubnetId: "7e95c4d6-d7af-424c-a3cf-2be10968fe81",
    		VpcId: "c5cd009b-9ba9-41f2-9a26-2b8c3f3ffd39",
    		AzCodes: listAzCodesbody,
    		SpecCode: "redis.ha.au1.large.2",
    		Capacity: float32(2),
    		EngineVersion: &engineVersionCreateInstanceBody,
    		Engine: "Redis",
    		Name: "dcs-demo",
    	}
    	response, err := client.CreateInstance(request)
    	if err == nil {
            fmt.Printf("%+v\n", response)
        } else {
            fmt.Println(err)
        }
    }
    

更多编程语言的SDK代码示例,请参见API Explorer的代码示例页签,可生成自动对应的SDK代码示例。

状态码

状态码

描述

200

下发创建缓存实例任务成功。

说明:

查看实例状态为RUNNING时,即缓存实例创建成功。

400

非法请求。

401

认证信息非法。

403

请求被拒绝访问。

404

所请求的资源不存在。

500

内部服务错误

错误码

请参见错误码