操作云硬盘EVS
引导式阅读
Java
操作云硬盘EVS
作者
Codelabs助理
上架时间
2023-11-13 03:42:29

场景介绍

基于华为云 Java SDK对云硬盘进行操作的代码示例,包括增(创建云硬盘)、删(删除云硬盘)、改(扩容云硬盘、挂载云硬盘、卸载云硬盘)、查(查询所有云硬盘/单个弹性云服务器的磁盘信息)等,完成了从云硬盘的创建(购买)到挂载、扩容,再到删除的整个生命周期的覆盖。

前提条件

获取AK/SK

开发者在使用前需先获取账号的ak、sk、endpoint、projectId。 您需要拥有华为云账号以及该账号对应的 Access Key(AK)和 Secret Access Key(SK)。请在华为云控制台“我的凭证-访问密钥”页面上创建和查看您的 AK/SK。更多信息请查看访问密钥。 endpoint 华为云各服务应用区域和各服务的终端节点,详情请查看地区和终端节点

由于本内容中包含ECS(弹性云服务器)、EVS(云硬盘)两个部分的Client,所以需要分别获取ecsEndpoint 和evsEndpoint。

projectId 云服务所在项目 ID ,根据你想操作的项目所属区域选择对应的项目 ID 。

运行环境

Java JDK 1.8 及其以上版本。

SDK 获取和安装

您可以通过如下方式获取和安装 SDK: 通过 Maven 安装依赖(推荐) 通过 Maven 安装项目依赖是使用 Java SDK 的推荐方法,首先您需要在您的操作系统中下载并安装 Maven ,安装完成后您只需在 Java 项目的 pom.xml 文件加入相应的依赖项即可。本示例使用ECS SDK及EVS SDK:

<dependency>   <groupId>com.huaweicloud.sdk</groupId>   <artifactId>huaweicloud-sdk-core</artifactId>   <version>[3.0.7-beta]</version> </dependency> <dependency>   <groupId>com.huaweicloud.sdk</groupId>   <artifactId>huaweicloud-sdk-ecs</artifactId>   <version>[3.0.7-beta]</version> </dependency> <dependency>   <groupId>com.huaweicloud.sdk</groupId>   <artifactId>huaweicloud-sdk-evs</artifactId>   <version>[3.0.7-beta]</version> </dependency>

通用准备

在使用SDK过程中的通用准备

  1. 导入依赖模块

    // 用户身份认证 import com.huaweicloud.sdk.core.auth.BasicCredentials; // 请求异常类 import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.core.exception.ServerResponseException; // Http配置 import com.huaweicloud.sdk.core.http.HttpConfig; // 导入相应产品的 {Service}Client import com.huaweicloud.sdk.ecs.v2.EcsClient; import com.huaweicloud.sdk.ecs.v2.model.*; //导入相应产品的 {Service}Client import com.huaweicloud.sdk.eip.v2.EvsClient; import com.huaweicloud.sdk.eip.v2.model.*; // 日志打印 import org.slf4j.Logger; import org.slf4j.LoggerFactory;
  2. 配置客户端属性

    HttpConfig config = HttpConfig.getDefaultHttpConfig(); config.withIgnoreSSLVerification(true);
  3. 初始化认证信息

    BasicCredentials auth = new BasicCredentials() .withAk(ak) .withSk(sk) .withProjectId(projectId);
  4. 初始EcsClient化客户端

    EcsClient ecsClient = EcsClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withEndpoint(ecsEndpoint) .build();
  5. 初始EcsClient化客户端

    EvsClient evsClient = EvsClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withEndpoint(evsEndpoint) .build();

示例代码

使用如下代码将进行云硬盘的创建/购买、查询、扩容、挂载、卸载、删除。

调用前请根据实际情况替换如下变量:

通用参数:{your ak string}、{your sk string}、{your ecs endpoint string} 、{your evs endpoint string} 以及 {your projectId string}

以及各个方法中包含的参数。

// 用户身份认证 import com.huaweicloud.sdk.core.auth.BasicCredentials; // 请求异常类 import com.huaweicloud.sdk.core.exception.ClientRequestException; import com.huaweicloud.sdk.core.exception.ServerResponseException; // Http配置 import com.huaweicloud.sdk.core.http.HttpConfig; // 导入相应产品的 {Service}Client import com.huaweicloud.sdk.ecs.v2.EcsClient; import com.huaweicloud.sdk.ecs.v2.model.*; // 日志打印 import com.huaweicloud.sdk.evs.v2.EvsClient; import com.huaweicloud.sdk.evs.v2.model.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Application { private static final Logger logger = LoggerFactory.getLogger(Application.class); public static void main(String[] args) { // 认证用的ak和sk直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); String ecsEndpoint = "{your ecs endpoint string}"; String evsEndpoint = "{your evs endpoint string}"; String projectId = "{your projectId string}"; // 配置客户端属性 HttpConfig config = HttpConfig.getDefaultHttpConfig(); config.withIgnoreSSLVerification(true); // 创建认证 BasicCredentials auth = new BasicCredentials() .withAk(ak) .withSk(sk) .withProjectId(projectId); //创建EcsClient实例并初始化 EcsClient ecsClient = EcsClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withEndpoint(ecsEndpoint) .build(); EvsClient evsClient= EvsClient.newBuilder() .withHttpConfig(config) .withCredential(auth) .withEndpoint(evsEndpoint) .build(); //云硬盘、磁盘 //创建云硬盘 //CreateVolume(evsClient); //查询所有云硬盘详情 //ListVolumesDetails(evsClient); //查询弹性云服务器磁盘信息 //GetServerBlockDevices(ecsClient); //扩容云硬盘 //ExpandVolume(evsClient); //挂载磁盘 //AttachServerVolume(ecsClient); //卸载磁盘 //DetachServerVolume(ecsClient); //删除磁盘 //DeleteVolume(evsClient); } private static void DeleteVolume(EvsClient client) { String volumeId = "{your volumeId string}";//云硬盘ID。 try { DeleteVolumeResponse response = client.deleteVolume(new DeleteVolumeRequest().withVolumeId(volumeId)); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void ExpandVolume(EvsClient client) { String volumeId = "{your volumeId string}";//云硬盘ID。 Integer newSize = 20;//扩容后的云硬盘大小,单位为GB try { ResizeVolumeResponse response = client.resizeVolume(new ResizeVolumeRequest().withVolumeId(volumeId) .withBody(new ResizeVolumeRequestBody().withOsExtend(new OsExtend().withNewSize(newSize)))); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void GetServerBlockDevices(EcsClient client) { String serverId = "{your serverId string}";//云服务器ID try { ListServerBlockDevicesResponse response = client.listServerBlockDevices(new ListServerBlockDevicesRequest().withServerId(serverId)); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void DetachServerVolume(EcsClient client) { String serverId = "{your serverId string}";//云服务器ID String volumeId = "{your volumeId string}";//待挂载磁盘的磁盘ID,UUID格式。云硬盘ID DetachServerVolumeRequest.DeleteFlagEnum deleteFlag = DetachServerVolumeRequest.DeleteFlagEnum._0;//是否强制卸载数据盘。是,值为“1”。否,值为“0”。默认值为0。 try { DetachServerVolumeResponse response = client.detachServerVolume(new DetachServerVolumeRequest().withServerId(serverId) .withVolumeId(volumeId).withDeleteFlag(deleteFlag)); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void ListVolumesDetails(EvsClient client) { try { ListVolumesDetailsResponse response = client.listVolumesDetails(new ListVolumesDetailsRequest()); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void CreateVolume(EvsClient client) { CreateVolumeOption.VolumeTypeEnum volumeType = CreateVolumeOption.VolumeTypeEnum.SATA;//云硬盘类型 String availabilityZone = "cn-north-1a";//可用区 Integer size = 10;//云硬盘大小。单位为GB Integer count = 1;//批量创云硬盘的个数。 boolean multiattach = false;//是否为共享云硬盘。true为共享盘,false为普通云硬盘。 String name = "{your volume name string}"; BssParamForCreateVolume.ChargingModeEnum chargingMode = BssParamForCreateVolume.ChargingModeEnum.POSTPAID;//按需付费 try { CreateVolumeResponse response = client.createVolume(new CreateVolumeRequest().withBody( (new CreateVolumeRequestBody().withVolume(new CreateVolumeOption() .withVolumeType(volumeType).withAvailabilityZone(availabilityZone).withSize(size) .withCount(count).withMultiattach(multiattach).withName(name)) .withBssParam(new BssParamForCreateVolume().withChargingMode(chargingMode))))); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void AttachServerVolume(EcsClient client) { String serverId = "{your serverId string}";//云服务器ID String volumeId = "{your volumeId string}";//待挂载磁盘的磁盘ID,UUID格式。 String device = "";//磁盘挂载点。可选。 try { AttachServerVolumeResponse response = client.attachServerVolume(new AttachServerVolumeRequest().withServerId(serverId) .withBody(new AttachServerVolumeRequestBody().withVolumeAttachment(new AttachServerVolumeOption() .withVolumeId(volumeId).withDevice(device)))); logger.info(response.toString()); }catch (ClientRequestException e){ LogError(e); } } private static void LogError(ClientRequestException e) { logger.error("HttpStatusCode: " + e.getHttpStatusCode()); logger.error("RequestId: " + e.getRequestId()); logger.error("ErrorCode: " + e.getErrorCode()); logger.error("ErrorMsg: " + e.getErrorMsg()); } }

运行示例

调用前请根据实际情况替换如下变量:

通用参数:{your ecs endpoint string} 、{your evs endpoint string} 以及 {your projectId string}

以及各个方法中包含的参数。

替换参数后,请根据需要执行的方法注释掉无关方法,并执行Run Application。

运行结果

输出结果:

创建云硬盘

[main] INFO Application - class CreateVolumeResponse {     jobId: {sample string}     orderId: null }

查询所有云硬盘详情

[main] INFO Application - class ListVolumesDetailsResponse {     count: 6     volumesLinks: null     volumes: [class VolumeDetail {         id: {sample string}         links: [class Link {             href: https://evs.cn-north-1.myhuaweicloud.com/v2/{sample string}/os-vendor-volumes/{sample string}             rel: self         }, class Link {             href: https://evs.cn-north-1.myhuaweicloud.com/{sample string}/os-vendor-volumes/{sample string}             rel: bookmark         }]         name: volumeTest         status: available         attachments: []         availabilityZone: cn-north-1a         osVolHostAttrHost: pod19.cn-north-1a#53         sourceVolid: null         snapshotId: null         description: null         createdAt: 2020-08-06T02:02:14.282629         osVolTenantAttrTenantId: {sample string}         volumeImageMetadata: {}         volumeType: SATA         size: 10         consistencygroupId: null         bootable: false         metadata: {}         updatedAt: 2020-08-06T02:02:17.572815         encrypted: false         replicationStatus: disabled         osVolumeReplicationExtendedStatus: null         osVolMigStatusAttrMigstat: null         osVolMigStatusAttrNameId: null         shareable: false         userId: {sample string}         serviceType: EVS         multiattach: false         dedicatedStorageId: null         dedicatedStorageName: null         tags: {}         wwn: null         enterpriseProjectId: 0     } }

查询弹性云服务器磁盘信息

[main] INFO Application - class ListServerBlockDevicesResponse {     attachableQuantity: class BlockDeviceAttachableQuantity {         freeScsi: 58         freeBlk: 22         freeDisk: 58     }     volumeAttachments: [class ServerBlockDevice {         bootIndex: 0         pciAddress: 0000:02:01.0         volumeId: {sample string}         device: /dev/vda         serverId: {sample string}         id: {sample string}         size: 40         bus: virtio     }, class ServerBlockDevice {         bootIndex: null         pciAddress: 0000:02:02.0         volumeId: {sample string}         device: /dev/vdb         serverId: {sample string}         id: {sample string}         size: 10         bus: virtio     }] }

扩容云硬盘

[main] INFO Application - class ResizeVolumeResponse {     jobId: {sample string}     orderId: null }

挂载磁盘

[main] INFO Application - class AttachServerVolumeResponse {     jobId: {sample string} }

卸载磁盘

[main] INFO Application - class DetachServerVolumeResponse {     jobId: {sample string} }

删除磁盘

[main] INFO Application - class DeleteVolumeResponse { "job_id": {sample string} }