Java的语言特点是什么(java语言的主要特点是什么)
588
2022-05-30
【前言】本文乃记一只小白的摸索之旅,路漫漫其修远兮,还望各路大神不吝赐教,就差手把手教教我!
一、简介
软件开发工具包(Software DevelopKit)包括代码以及示例,用户可以自行选择语言创建OpenStack云应用。
目前SDK的语言支持:Java、Python、Go。您可以使用任意一种熟知的SDK,本文将介绍Java SDK
二、环境准备
1、 适用于 JDK1.7+ ,建议使用 JDK1.8
2、 获取Java SDK(jar包)及其介绍文档
登录以下网站获取Python OpenStack SDK 的官方文档
http://developer.huaweicloud.com/dev/sdk?all
3、 获取相关API文档
登录华为云官网 查看各个云服务的接口参考文档。
http://support.huaweicloud.com
通过这些文档,可以学习云平台所支持的API参数。
4、 获取华为云endpoint信息
endpoint/AZ信息见
http://developer.huaweicloud.com/endpoint.html
5、 Java SDK项目的源代码,请访问如下地址
https://github.com/huawei/openstack4j
三、OpenStack原生CLI命令行使用指导
1、获取华为云IAM鉴权信息,projectId/userDomainId参数获取方法:
华为云控制台-用户-我的凭证处
2、安装开源CLI客户端
华为云OpenStack基于社区Mitaka版本,能够适配Mitaka版本的client端,需要在Linux服务器上安装python包,所需版本如下:
python-openstackclient: 3.2.1
python-novaclient: 6.0.0
python-glanceclient: 2.5.0
python-keystoneclient: 3.5.1
python-neutronclient: 6.0.0
python-cinderclient: 1.9.0
python-heatclient: 1.5.1
安装命令示例:pip install python-novaclient==6.0.0
环境变量配置:
export OS_USERNAME=wanglianmin # 输入User信息
export OS_USER_DOMAIN_NAME=wanglianmin # 输入Domain信息
export OS_PROJECT_DOMAIN_NAME=wanglianmin # 输入Domain信息
export OS_PASSWORD=XXXXXX # 输入华为云账号密码
export OS_TENANT_NAME=cn-north-1 # 输入Tenant信息
export OS_PROJECT_NAME=cn-north-1 # 输入Project信息
export OS_AUTH_URL=https://iam.cn-north-1.myhwclouds.com/v3 # 输入IAM的endpoint,使用v3鉴权接口
# No changes needed beyond this point
export NOVA_ENDPOINT_TYPE=publicURL
export OS_ENDPOINT_TYPE=publicURL
export CINDER_ENDPOINT_TYPE=publicURL
export OS_VOLUME_API_VERSION=2
export OS_IDENTITY_API_VERSION=3
export OS_IMAGE_API_VERSION=2
3、创建Ecs
3.1 获取Flavor ID
通过执行os.compute().flavors().list() 命令,查询所有flavors,并使用符合要求的Flavor ID 创建ECS。
3.2 创建安全组
关于如何创建安全组,请参见如何创建安全组?
3.3 创建秘钥对
如何创建秘钥对,详情请参见如何在控制台上创建秘钥对?
3.4 创建ECS。
您可以使用以下代码创建ECS。通过使用WaitForServerStatus,您可以持续查询ECS的状态,直至ECS达到规定的状态或者查询超时为止。可以根据实际要求修改参数。在以下例子中,超时间隔默认为10分钟。
private void createTestServer() throws IOException { ArrayList networkList = new ArrayList(); networkList.add(net.getId()); ServerCreate serverCreate = Builders.server().name("vm-name") .flavor("flavorId") .image("imageId") .networks(networkList) .build(); Server server = os.compute().servers().boot(serverCreate); os.compute().servers().waitForServerStatus(server.getId(), Server.Status.ACTIVE, 10, TimeUnit.MINUTES); }
3.5 将EIP绑定至ECS
查询ECS的端口ID。
您可以根据以下代码,查询创建EIP所用的ECS端口ID。
List extends InterfaceAttachment> nicID = os.compute().servers().interfaces().list(server.getId()); String port_id = nicID.get(0).getPortId();
创建EIP。
根据以下代码创建EIP,EIP创建成功后,其可以自动绑定至ECS上,因为您在创建EIP时已经指定了ECS端口ID。
由于ECS创建需要花费一定的时间,所以您需要检查ECS状态。
NetFloatingIP fip = os.networking().floatingip().create(Builders.netFloatingIP().floatingNetworkId("external_network_id").portId(port_id).build()); if (os.networking().floatingip().get(fip.getId()).getStatus().equals("ACTIVE")) { System.out.println("EIP API responsed Success"); } // judge fip is created successfully int count = 1; boolean createFlat = false; while (count < 10) { if (os.networking().floatingip().get(fip.getId()).getStatus().toString().equals("ACTIVE")) { System.out.println("Confirmed EIP Create Success"); createFlat = true; break; } count++; Thread.sleep(1000); System.out.println(os.networking().floatingip().get(fip.getId()).getStatus()); } if (!createFlat) { System.out.println("EIP is not successfully created"); }
external_network_id 是指外部网络ID,
外部网络是属性router:external被设定为true的网络。该网络可用于分配EIP。在将EIP添加到ECS上之后,即可通过互联网访问ECS。
无需创建外部网络,因为外部网络已经存在。
通过执行API: GET /v2.0/networks?router:external=True命令,查询创建EIP所用网络的ID。
您可以根据以下代码,从ECS解绑EIP。
解绑操作需要花费一定的时间,并且只有在被解绑后,EIP才可以删除。如果在解绑过程中您删除了EIP,则可能会上报错误消息。
// after the fip is ACTIVE,Do the remove action ActionResponse removeAction = os.compute().floatingIps().removeFloatingIP(server, fip.getFloatingIpAddress()); if (removeAction.isSuccess()) { System.out.println("Remove Response Action Success"); } // judge the EIP disassociate successfully int j = 1; boolean removeFlag = false; while (j < 10) { if (os.networking().floatingip().get(fip.getId()).getPortId() == null && os.networking().floatingip().get(fip.getId()).getStatus().toString().equals("DOWN")) { removeFlag = true; System.out.println("Confirmed disassociate successfuly"); break; } Thread.sleep(1000); j++; } if (!removeFlag) { System.out.println("Disassociate failure"); }
附:ECS弹性云服务器的示例
import java.util.List;
import java.util.stream.Collectors;
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import com.huawei.openstack4j.api.Builders;
import com.huawei.openstack4j.api.OSClient.OSClientV3;
import com.huawei.openstack4j.api.types.ServiceType;
import com.huawei.openstack4j.core.transport.Config;
import com.huawei.openstack4j.model.common.ActionResponse;
import com.huawei.openstack4j.model.common.Identifier;
import com.huawei.openstack4j.openstack.OSFactory;
import com.huawei.openstack4j.openstack.identity.internal.OverridableEndpointURLResolver;
import com.huawei.openstack4j.model.compute.Action;
import com.huawei.openstack4j.model.compute.RebootType;
import com.huawei.openstack4j.model.compute.Server;
import com.huawei.openstack4j.model.compute.Server.Status;
import com.huawei.openstack4j.model.compute.ServerCreate;
public class Demo_for_WebSite {
private static final String LANGUAGE = "zh-cn";
public static void main(String[] args) {
/* 第一步:填入华为云区域的endpoint
*/
OverridableEndpointURLResolver endpointResolver = new OverridableEndpointURLResolver();
endpointResolver.addOverrideEndpoint(ServiceType.VOLUME_BACKUP,
"https://vbs.cn-north-1.myhuaweicloud.com/v2/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.DNS,
"https://dns.myhuaweicloud.com/v2");
endpointResolver.addOverrideEndpoint(ServiceType.AUTO_SCALING,
"https://as.cn-north-1.myhuaweicloud.com/autoscaling-api/v1/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.CLOUD_EYE,
"https://ces.cn-north-1.myhuaweicloud.com/V1.0/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.LOAD_BALANCER,
"https://elb.cn-north-1.myhuaweicloud.com/v1.0/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.MAP_REDUCE,
"https://mrs.cn-north-1.myhuaweicloud.com/v1.1/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.KEY_MANAGEMENT,
"https://kms.cn-north-1.myhuaweicloud.com/v1.0/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.CLOUD_TRACE,
"https://cts.cn-north-1.myhuaweicloud.com/v1.0/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.ANTI_DDOS,
"https://antiddos.cn-north-1.myhuaweicloud.com/v1/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.Notification,
"https://smn.cn-north-1.myhuaweicloud.com/v2/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.MessageQueue,
"https://dms.cn-north-1.myhuaweicloud.com/v1.0/%(project_id)s");
endpointResolver.addOverrideEndpoint(ServiceType.MAAS,
"https://maas.cn-north-1.myhuaweicloud.com/v1/%(project_id)s/objectstorage");
endpointResolver.addOverrideEndpoint(ServiceType.DATABASE, "https://rds.cn-north-1.myhuaweicloud.com");
/* 第二步: 配置鉴权信息(以华北区为例)
* user为用户名
* projectId为华为云控制台-账户中心-基本信息-管理我的凭证-项目列表中华北区的项目ID
* userDomainId为华为云控制台-账户中心-基本信息-管理我的凭证的账户ID
* authURL为IAM服务华北区的域名
*/
String user = "wanglianmin";
String password = "XXXXXX";
String projectId = "74610f3a5ad941998e91f076297ecf27";
String userDomainId = "2aa29cbca17a4822abd096610e378ffa";
String authUrl = "https://iam.cn-north-1.myhuaweicloud.com/v3";
// 第三步: 初始化一个连接
OSFactory.enableHttpLoggingFilter(true); //调试用,可以显示request body和response body
Config config = Config.newConfig().withEndpointURLResolver(endpointResolver).withLanguage(LANGUAGE)
.withSSLVerificationDisabled();
OSClientV3 osclient = OSFactory.builderV3().withConfig(config).endpoint(authUrl)
.credentials(user, password, Identifier.byId(userDomainId)).scopeToDomain(Identifier.byId(userDomainId))
.scopeToProject(Identifier.byId(projectId)).authenticate();
// 第四步: 过滤查询弹性云服务器列表
Map
filter_name.put("name", "ecs");
filter_name.put("status", "ACTIVE");
List extends Server> servers = osclient.compute().servers().list(filter_name);
System.out.println(servers);
// 第五步:创建虚拟机,填入所需参数;停止、启动、重启、删除虚拟机
String imageId = "1189efbf-d48b-46ad-a823-94b942e2a000";
String flavorId = "s2.small.1";
String networkId = "ef039b60-6a14-42d1-963b-687b627fea08";
String imageId_Windows = "201150a6-479e-45f3-8a4c-fe91855758f0";
// 创建Linux密码虚拟机,目前密码使用user-data参数传入,将来会统一使用adminPass参数
String userData_org = "#!/bin/bash \r\n echo ´root:P@ssWr0d123´ | chpasswd ;";
byte[] userData_byte = userData_org.getBytes();
String userData = new BASE64Encoder().encode(userData_byte);
// generate networkList
ArrayList
networkList.add(networkId);
// generate server body
ServerCreate sc_Linux = Builders.server().name("zt-Linux-test-sdk").flavor(flavorId).image(imageId).availabilityZone("cn-north-1b").userData(userData).networks(networkList).build();
System.out.println("New Server body " + sc_Linux);
Server newServer = osclient.compute().servers().boot(sc_Linux);
osclient.compute().servers().waitForServerStatus(newServer.getId(), Status.ACTIVE, 10, TimeUnit.MINUTES);
System.out.println("New Server " + newServer);
// 创建Windows密码虚拟机,目前密码使用metadata参数传入,将来会统一使用adminPass参数
ServerCreate sc_Windows = Builders.server().name("zt-Windows-test-sdk").flavor(flavorId).image(imageId_Windows).availabilityZone("cn-north-1b").addMetadataItem("admin_pass", "P@ssWr0d123").networks(networkList).build();
System.out.println("New Server body " + sc_Windows);
Server newServer_Windows = osclient.compute().servers().boot(sc_Windows);
osclient.compute().servers().waitForServerStatus(newServer_Windows.getId(), Status.ACTIVE, 10, TimeUnit.MINUTES);
System.out.println("New Server " + newServer_Windows);
// 停止虚拟机
ActionResponse repStop = osclient.compute().servers().action(newServer.getId(), Action.STOP);
if(repStop.isSuccess()) {
System.out.println("Stop the server success, status = " + newServer.getId() + newServer.getVmState());
}else {
System.out.println("Stop the server failed " + newServer.getId());
}
osclient.compute().servers().waitForServerStatus(newServer.getId(), Status.SHUTOFF, 3, TimeUnit.MINUTES);
// 启动虚拟机
ActionResponse repStart = osclient.compute().servers().action(newServer.getId(), Action.START);
if(repStart.isSuccess()) {
System.out.println("Start the server success, status = " + newServer.getId() + newServer.getVmState());
}else {
System.out.println("Start the server failed " + newServer.getId());
}
osclient.compute().servers().waitForServerStatus(newServer.getId(), Status.ACTIVE, 3, TimeUnit.MINUTES);
// 重启虚拟机
ActionResponse repReboot = osclient.compute().servers().reboot(newServer.getId(), RebootType.SOFT);
if(repReboot.isSuccess()) {
System.out.println("Reboot the server success, status = " + newServer.getId() + newServer.getVmState());
}else {
System.out.println("Reboot the server failed " + newServer.getId());
}
osclient.compute().servers().waitForServerStatus(newServer.getId(), Status.ACTIVE, 3, TimeUnit.MINUTES);
// 删除虚拟机
ActionResponse repDelete = osclient.compute().servers().delete(newServer.getId());
if(repDelete.isSuccess()) {
System.out.println("Delete the server success, status = " + newServer.getId() + newServer.getVmState());
}else {
System.out.println("Delete the server failed " + newServer.getId());
}
ActionResponse repDelete_Windows = osclient.compute().servers().delete(newServer_Windows.getId());
if(repDelete_Windows.isSuccess()) {
System.out.println("Delete the server success, status = " + newServer_Windows.getId() + newServer.getVmState());
}else {
System.out.println("Delete the server failed " + newServer_Windows.getId());
}
}
}
云市场
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。