一、概念

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"]}]
}

常用公有云接入——谷歌相关推荐

  1. 常用公有云接入——华为

    一.介绍 1.什么是弹性云服务器? 弹性云服务器是由CPU.内存.镜像.云硬盘组成的一种可随时获取.弹性可扩展的计算服务器,同时它结合虚拟私有云.虚拟防火墙.数据多副本保存等能力,为您打造一个高效.可 ...

  2. 常用公有云接入——腾讯

    一.ES术语表 本文档涉及的一些常用术语如下: 术语 全称 中文 说明 Instance Instance 实例 指代一台云服务器. Region Region 地域 表示资源所在的地域,每个地域包含 ...

  3. 常用公有云接入——亚马逊

    一.什么是 Amazon EC2? Amazon Elastic Compute Cloud (Amazon EC2) 在 Amazon Web Services (AWS) 云中提供可扩展的计算容量 ...

  4. 常用公有云接入——阿里

    一.术语 中文 英文 说明 地域 Region 阿里云建设的数据中心.资源创建成功后无法更换地域. 可用区 Zone 同一地域内,电力和网络互相独立的物理数据中心.一个地域下可以有多个可用区.同一地域 ...

  5. 常用公有云接入——AZURE

    一.概念 1.订阅 可以使用订阅为组织内的团队提供访问开发环境(即测试.生产.开发.临时部署等)和项目的权限.针对每个应用程序环境创建不同的订阅,并为每个订阅分配不同的服务管理员帐户,这是保护每个环境 ...

  6. 公有云玩家大阅兵,谁能玩到最后?

    前言 张晓龙  网易杭州研究院-前台技术中心 当前云计算不再只停留在概念上,而是在中国乃至全球都有巨大市场的重要业务.随着互联网+成为中国的国家战略,云计算已经成为实现互联网+的基础保证.目前在中国公 ...

  7. 公有云的未来:要么统治世界,要么灭亡

    长久以来,私有云厂商都被一朵乌云笼罩着:私有云是否是一个伪命题,这个世界是否终将被公有云统治?无论如何振振有词,当2006年3月14日亚马逊向全世界宣布其公有云服务AWS时,IT的历史车轮就碾入了公有 ...

  8. 阿里热修复之Sophix——公有云发布版集成步骤

    Sophix 公有云接入 去年的时候写的一篇阿里云热修复的文章,那时它还是在公测阶段,一直没能投产,而今,公司项目需要集成已经投产的阿里Sophix功能,所以再次集成了一遍,记录下了步骤和遇到的一些问 ...

  9. Gartner 发布容器公有云竞争格局报告 | 云原生生态周报 Vol. 44

    作者 | 王思宇.陈洁 业界要闻 Gartner 容器报告:阿里云与 AWS 并列第一,领先微软.谷歌 近日,国际知名调研机构 Gartner 发布 2020 年容器公有云竞争格局报告,阿里云再度成为 ...

最新文章

  1. 安装oracle并且小总结oracle sql
  2. 使用JDBC,完成对如下表的增删改查操作
  3. PPT 下载 | 神策数据朱静芸:电商行业精细化运营四大场景
  4. java安全编码指南之:异常处理
  5. Java获取请求客户端的真实IP地址
  6. python嵌入shell代码_小白进!嵌入式开发如何快速入门?
  7. python读取qq客户端消息_使用 Python 读取 QQ 消息
  8. 会员无损音乐各种格式转换成mp3等格式
  9. pycharm主题背景图片设置,让你的界面酷起来!
  10. 卡内基梅隆 计算机音乐,卡内基梅隆大学音乐技术专业申请要求
  11. Premiere Pro 2022转字幕语言包
  12. 中国象棋java大作业doc_《java语言程序设计》课程设计-中国象棋对弈系统(源码).doc...
  13. 网上订鲜花怎么配送?鲜花配送为何首选顺丰同城急送?
  14. can't find lxxx解决办法
  15. 钢琴软件c语言源代码,使用C语言编写钢琴小程序
  16. css -- 为什么:last-child 无效?
  17. Git和GitHub学习笔记 V2.0(更新中...)
  18. 激光雕刻机图片解析C#上位机stm32f407控制板源码
  19. Java程序员学习资料分享,等你来收藏!
  20. go语言web开发1 相关知识

热门文章

  1. css less 不要作用到子对象_使用Less实现网站主题切换
  2. jdk解压版_命令行版的斗地主你玩过没?
  3. 软件构造学习笔记-第十二周
  4. 买卖股票类问题动态规划解法(Leetcode题解-Python语言)
  5. [mybatis]Mapper XML Files_CUD
  6. [PAT乙级]1041 考试座位号
  7. UVA - 548 Tree
  8. 高等数学上-赵立军-北京大学出版社-题解-练习5.8
  9. 多重背包问题以及二进制优化
  10. hystrix隔离策略对比