常用公有云接入——谷歌

一、概念

1、项目

一个账号有唯一的项目,所有虚拟机都在project里面建。

2、计算引擎

虚拟机资源。

 

二、创建方式

1、页面控制台

2、gcloud命令行

3、REST API

4、SDK

 

三、Java SDK

1、创建API服务凭据,并下载P12文件

2、Maven

         <dependency><groupId>com.google.api-client</groupId><artifactId>google-api-client</artifactId><version>1.28.0</version></dependency><dependency><groupId>com.google.apis</groupId><artifactId>google-api-services-compute</artifactId><version>v1-rev20190107-1.28.0</version></dependency>

3、计算引擎会话

  public static Compute getCompute() {String appName = "your app name";String serviceAccountId = "your service account id";String proxyHost = "my.proxy.com";String proxyPort = "8090";//国内需要代理System.setProperty("com.google.api.client.should_use_proxy","true");System.setProperty("https.proxyHost",proxyHost);System.setProperty("https.proxyPort",proxyPort);try {HttpTransport transport = new NetHttpTransport.Builder().trustCertificates(GoogleUtils.getCertificateTrustStore()).build();JacksonFactory jsonFactory = JacksonFactory.getDefaultInstance();List<String> scopes = new ArrayList<>();// Set Google Cloud Storage scope to Full Control.scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL);// Set Google Compute Engine scope to Read-write.scopes.add(ComputeScopes.COMPUTE);// Authenticate using Google Application Default Credentials.GoogleCredential credential = new GoogleCredential.Builder().setTransport(transport).setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountId).setServiceAccountScopes(scopes).setServiceAccountPrivateKeyFromP12File(List.class.getResourceAsStream("/my-rojectId-384742064.p12")).build();// Create Compute Engine object for listing instances.Compute compute = new Compute.Builder(transport, jsonFactory, credential).setApplicationName(appName).build();return compute;} catch (GeneralSecurityException | IOException e) {e.printStackTrace();}return null;}

4、创建虚拟机

 public static void create() {Compute compute = getCompute();String googleDomain ="https://www.googleapis.com";String region = "asia-south1";String zone = "asia-south1-a";String network = "first-network";String subNet = "first-subnet";String imageId = "projects/debian-cloud/global/images/debian-9-stretch-v20190326";String osDiskName = "first-os-disk";Integer osDiskSize = 30;String osDiskType = "pd-standard";String vmName = "first-vm";String vmType = "n1-standard-1";String publicIpName = "first-public-ip";String dataDiskName = "first-data-disk";String dataDiskType = "pd-standard";Long dataDiskSize = 200L;String projectId = "your projectId";try {Instance instance = new Instance();instance.setName(vmName);instance.setZone(zone);instance.setMachineType("zones/" + zone + "/machineTypes/" + vmType);NetworkInterface networkInterface = new NetworkInterface();networkInterface.setNetwork("global/networks/" + network);networkInterface.setSubnetwork("regions/" + region + "/subnetworks/" + subNet);List<AccessConfig> configs = new ArrayList<>();AccessConfig config = new AccessConfig();String NETWORK_INTERFACE_CONFIG = "ONE_TO_ONE_NAT";config.setType(NETWORK_INTERFACE_CONFIG);config.setName(publicIpName);config.setNetworkTier("PREMIUM");configs.add(config);networkInterface.setAccessConfigs(configs);instance.setNetworkInterfaces(Collections.singletonList(networkInterface));List<AttachedDisk> attachedDisks = new ArrayList<>();//系统盘AttachedDisk osDisk = new AttachedDisk();osDisk.setBoot(true);osDisk.setAutoDelete(true);osDisk.setType("PERSISTENT");AttachedDiskInitializeParams osParams = new AttachedDiskInitializeParams();osParams.setDiskName(osDiskName);osParams.setSourceImage(imageId);osParams.setDiskType("zones/" + zone + "/diskTypes/" + osDiskType);osParams.setDiskSizeGb(osDiskSize.longValue());osDisk.setInitializeParams(osParams);attachedDisks.add(osDisk);//数据盘AttachedDisk dataDisk = new AttachedDisk();dataDisk.setBoot(false);dataDisk.setAutoDelete(true);dataDisk.setType("PERSISTENT");AttachedDiskInitializeParams dataParams = new AttachedDiskInitializeParams();// Assign the Persistent Disk the same name as the VM Instance.osParams.setDiskName(dataDiskName);osParams.setDiskType("zones/" + zone + "/diskTypes/" + dataDiskType);osParams.setDiskSizeGb(dataDiskSize);dataDisk.setInitializeParams(dataParams);attachedDisks.add(dataDisk);instance.setDisks(attachedDisks);ServiceAccount account = new ServiceAccount();account.setEmail("default");List<String> scopes = new ArrayList<>();scopes.add(googleDomain + "/auth/devstorage.full_control");scopes.add(googleDomain + "/auth/compute");account.setScopes(scopes);instance.setServiceAccounts(Collections.singletonList(account));//ssh串行接口/*Metadata.Items items = new Metadata.Items();items.setKey("serial-port-enable");items.setValue("true");Metadata metadata = new Metadata();metadata.setItems(Arrays.asList(items));instance.setMetadata(metadata);*/Compute.Instances.Insert insert = compute.instances().insert(projectId, zone, instance);Operation operation = insert.execute();operation = blockUntilComplete(compute, operation, projectId,5 * 60 * 1000);if (operation != null && operation.getError() != null)throw  new RuntimeException("创建失败");} catch (Exception ex) {ex.printStackTrace();}}private static Operation blockUntilComplete(Compute compute, Operation operation, String projectId, long timeoutMil) throws Exception {long start = System.currentTimeMillis();final long pollInterval = 3 * 1000;String zone = operation.getZone();  // null for global/regional operationsif (zone != null) {String[] bits = zone.split("/");zone = bits[bits.length - 1];}String region = operation.getRegion();if (region!=null){String[] bits = region.split("/");region = bits[bits.length - 1];}String status = operation.getStatus();String opId = operation.getName();while (operation != null && !status.equals("DONE")) {Thread.sleep(pollInterval);long elapsed = System.currentTimeMillis() - start;if (elapsed >= timeoutMil) {throw new InterruptedException("Timed out waiting for operation to complete");}if (zone != null) {Compute.ZoneOperations.Get get = compute.zoneOperations().get(projectId, zone, opId);operation = get.execute();} else if(region!=null){Compute.RegionOperations.Get get = compute.regionOperations().get(projectId, region, opId);operation = get.execute();}else {Compute.GlobalOperations.Get get = compute.globalOperations().get(projectId, opId);operation = get.execute();}if (operation != null) {status = operation.getStatus();}}return operation;}

5、删除虚拟机

public  static void delete() {String zone = "asia-south1-a";String vmName = "first-vm";String projectId = "your projectId";Compute compute = getCompute();try {Compute.Instances.Delete delete = compute.instances().delete(projectId, zone, vmName);Operation operation = delete.execute();operation = blockUntilComplete(compute, operation, projectId,5 * 60 * 1000);if (operation != null && operation.getError() != null)throw  new RuntimeException("删除失败");}catch (Exception ex){throw new RuntimeException(ex);}}

6、查询虚拟机

    public static void getVm(){String zone = "asia-south1-a";String vmName = "first-vm";String projectId = "your projectId";Compute compute = getCompute();try {Compute.Instances.Get get  = compute.instances().get(projectId, zone,vmName);Instance instance = get.execute();//STAGING, RUNNING, STOPPING, STOPPED, SUSPENDING, SUSPENDED, and TERMINATEDString status = instance.getStatus();} catch (IOException e) {e.printStackTrace();}}

7、停止,启动操作

public  static void op() {String zone = "asia-south1-a";String vmName = "first-vm";String projectId = "your projectId";Compute compute = getCompute();try {Compute.Instances.Stop stop = compute.instances().stop(projectId, zone,vmName);Operation operation = stop.execute();if (operation != null && operation.getError() != null)throw  new RuntimeException("停止失败");Compute.Instances.Start start = compute.instances().start(projectId, zone,vmName);Operation startOp = start.execute();if (startOp != null && startOp.getError() != null)throw  new RuntimeException("启动失败");}catch (Exception ex){throw new RuntimeException(ex);}}

8、设置静态公网IP

 public static void modify() {String region = "asia-south1";String zone = "asia-south1-a";String vmName = "first-vm";String projectId = "your projectId";Compute compute = getCompute();try {Compute.Instances.Get get = compute.instances().get(projectId, zone, vmName);Instance instance = get.execute();for (NetworkInterface n : instance.getNetworkInterfaces()) {for (AccessConfig config : n.getAccessConfigs()) {if (!Strings.isNullOrEmpty(config.getNatIP())) {Address address = new Address();address.setName(config.getName());address.setAddress(config.getNatIP());Compute.Addresses.Insert inset = compute.addresses().insert(projectId, region, address);Operation op = inset.execute();if (op != null && op.getError() != null)throw new RuntimeException("绑定公网IP失败");}}}} catch (Exception ex) {ex.printStackTrace();}}

 

四、REST API

使用OAuth 2.0访问Google API

Compute Engine API

保留静态外部 IP 地址

保留静态内部 IP 地址

资源引用(实例与实例组、实例组与负载均衡等引用关系·)

 

创建实例:

POST https://www.googleapis.com/compute/v1/projects/my-projectId/zones/us-east1-b/instances
{"kind": "compute#instance","name": "instance-1","zone": "projects/my-projectId/zones/us-east1-b","machineType": "projects/my-projectId/zones/us-east1-b/machineTypes/n1-standard-1","displayDevice": {"enableDisplay": false},"metadata": {"kind": "compute#metadata","items": []},"tags": {"items": []},"disks": [{"kind": "compute#attachedDisk","type": "PERSISTENT","boot": true,"mode": "READ_WRITE","autoDelete": true,"deviceName": "instance-1","initializeParams": {"sourceImage": "projects/debian-cloud/global/images/debian-9-stretch-v20190326","diskType": "projects/my-projectId/zones/us-east1-b/diskTypes/pd-standard","diskSizeGb": "10"}}],"canIpForward": false,"networkInterfaces": [{"kind": "compute#networkInterface","subnetwork": "projects/my-projectId/regions/us-east1/subnetworks/default","accessConfigs": [{"kind": "compute#accessConfig","name": "External NAT","type": "ONE_TO_ONE_NAT","networkTier": "PREMIUM"}],"aliasIpRanges": []}],"description": "","labels": {},"scheduling": {"preemptible": false,"onHostMaintenance": "MIGRATE","automaticRestart": true,"nodeAffinities": []},"deletionProtection": false,"serviceAccounts": [{"email": "12345-compute@developer.gserviceaccount.com","scopes": ["https://www.googleapis.com/auth/devstorage.read_only","https://www.googleapis.com/auth/logging.write","https://www.googleapis.com/auth/monitoring.write","https://www.googleapis.com/auth/servicecontrol","https://www.googleapis.com/auth/service.management.readonly","https://www.googleapis.com/auth/trace.append"]}]
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/323670.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

elementui实现表格单选功能

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 需求是这样的&#xff1a;用户单击购买产品的按钮时&#xff0c;会出现一个产品的列表&#xff0c;但是呢只能买一种产品&#xff0c;暂时不可以多选。效果如下所示&#xff1a; 原来…

element-ui实现表格单选的功能

“大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂”前言现在是&#xff1a;2022年4月20日13:33:23需求是这样的&#xff1a;用户单击购买产品的按钮时&#xff0c;会出现一个产品的列表&#xff0c;但是呢只能买一种产品&#xff0c;暂时不…

ASP.NET Core Razor 视图组件

视图组件简介 在新的ASP.NET Core MVC中&#xff0c;视图组件类似于局部视图&#xff0c;但它们更强大。视图组件不使用模型绑定&#xff0c;仅依赖于您在调用时提供的数据。 视图组件特性&#xff1a; 呈现页面响应的某一部分而不是整个响应包括在控制器和视图之间发现的关…

三个好用的并发工具类

转载自 三个好用的并发工具类 以前的文章中&#xff0c;我们介绍了太多的底层原理技术以及新概念&#xff0c;本篇我们轻松点&#xff0c;了解下 Java 并发包下、基于这些底层原理的三个框架工具类。 它们分别是&#xff1a; 信号量 Semaphore 倒计时门栓 CountDownLatch …

Error Handling in ASP.NET Core

前言 在程序中&#xff0c;经常需要处理比如 404&#xff0c;500 &#xff0c;502等错误&#xff0c;如果直接返回错误的调用堆栈的具体信息&#xff0c;显然大部分的用户看到是一脸懵逼的&#xff0c;你应该需要给用户返回那些看得懂的界面。比如&#xff0c;“当前页面不存在…

基于python的selenium

一.安装 安装WebDriver 查看chrome版本号&#xff0c;设置-帮助-关于Google chrome&#xff0c;找到版本号。 可以到这个网站进行下载对应版本的chromedriver,如果chrome浏览器版本过高,可以下载最新版的chromedriver进行使用 Chrome for Testing availability 下载下来之后…

多信息登录、检测用户信息是否完善且引导补全

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注&#xff1a;穆雄雄的博客 前言 现在是2022年4月28日13:41:29&#xff01; 今天分享两块内容。 1.需求&#xff1a;用户可以通过手机号、邮箱来注册我们的系统&#xff0c;用户完成之后&#xff0c;可以去完善自己的个人信息…

PNG 图片压缩原理解析

转载自 PNG 图片压缩原理解析 什么是PNG PNG的全称叫便携式网络图型&#xff08;Portable Network Graphics&#xff09;是目前最流行的网络传输和展示的图片格式&#xff0c;原因有如下几点&#xff1a; 无损压缩&#xff1a;PNG图片采取了基于LZ77派生算法对文件进行压缩&…

element ui实现多层级复杂表单的操作(添加与回显)之表单操作交互操作

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年5月3日11:47:15&#xff01;劳动节假期已经过去了三天了&#xff0c;今天是被封家里的第7天&#xff0c;也是解封的第一天。 说实话&#xff0c;在家里的工作效率一点都…

TypeScript 2.5 发布,增加语言级重构

在 TypeScript 2.5 版本中&#xff0c;Microsoft 专注于提高开发人员的生产力&#xff0c;其范围已经超出了代码编辑器所提供的常见功能。 习惯于类型语言&#xff08;如 C&#xff03;&#xff09;的开发人员喜欢使用那些可以轻松执行常见重构的工具。现在 TypeScript 可以利…

element ui实现多层级复杂表单的操作(添加与回显)之添加功能实现

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年5月3日13:35:15&#xff01;文接上篇。[element ui实现多层级复杂表单的操作&#xff08;添加与回显&#xff09;之表单操作交互操作](element ui实现多层级复杂表单的操…

Entity Framework Core Like 查询揭秘

在Entity Framework Core 2.0中增加一个很酷的功能&#xff1a;EF.Functions.Like()&#xff0c;最终解析为SQL中的Like语句&#xff0c;以便于在 LINQ 查询中直接调用。 不过Entity Framework 中默认提供了StartsWith、Contains和EndsWith方法用于解决模糊查询&#xff0c;那…

element ui实现多层级复杂表单的操作(添加与回显)之回显功能实现

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年5月3日17:02:30&#xff01;文接上两篇。 [element ui实现多层级复杂表单的操作&#xff08;添加与回显&#xff09;之表单操作交互操作](element ui实现多层级复杂表单…

在Mac的Docker中运行DotNetCore2.0

最近学习Angular4&#xff0c;服务端准备使用DotNetCore API来实现&#xff0c;本文简单介绍下在Mac中怎样将DotNetCore程序部署在Docker中&#xff0c;并使用Nginx做反向代理让程序可以跑起来。 具体步骤如下 安装Docker拉取DotNetCore镜像使用VS For Mac创建DotNetCore应用…

springboot实现复杂业务下的更新操作

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年5月4日19:25:55&#xff01;今天写了个这样的功能&#xff1a; 某用户在一天内有多个训练项目&#xff0c;比如&#xff1a;晨跑&#xff0c;有氧训练&#xff0c;跳绳这…

elementui解决el-dialog不清空内容的问题,el-dialog关闭时销毁子组件

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年5月5日22:48:21&#xff01; 今天在使用element-ui中的el-dialog的时候遇到了个这样的问题&#xff1a;页面上点击添加的按钮&#xff0c;弹出el-dialog对话框&#xff…

MySQL 中的重做日志,回滚日志以及二进制日志的简单总结

转载自 MySQL 中的重做日志&#xff0c;回滚日志以及二进制日志的简单总结 MySQL中有六种日志文件&#xff0c;分别是&#xff1a;重做日志&#xff08;redo log&#xff09;、回滚日志&#xff08;undo log&#xff09;、二进制日志&#xff08;binlog&#xff09;、错误日志…

c语言分离三位数

#include<stdio.h> main(){ int k,l,m,n;printf("请输入一个三位数"); scanf("%d",&k);lk/100;mk/10%10;nk%10;printf("这个三位数的百位是:%d\n",l);printf("这个三位数的十位是:%d\n",m);printf("这个三位数的个位是…

分布式ID自增算法 Snowflake

近在尝试EF的多数据库移植&#xff0c;但是原始项目中主键用的Sqlserver的GUID。MySQL没法移植了。 其实发现GUID也没法保证数据的递增性&#xff0c;又不太想使用int递增主键&#xff0c;就开始探索别的ID形式。 后来发现twitter的Snowflake算法。 一开始我尝试过直接引用N…

java中,根据指定日期显示出前n天的日期

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 今天分享的是&#xff1a;在java中&#xff0c;根据指定日期显示出前n天的日期 效果如下&#xff1a; 大家注意观察上面的时间&#xff0c;我传入的时间是&#xff1a;2022年5月9日21:28:…