一、概念

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 operations
        if (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 TERMINATED
            String 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"
      ]
    }
  ]
}
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐