日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

常用公有云接入——谷歌

發(fā)布時(shí)間:2023/12/3 编程问答 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 常用公有云接入——谷歌 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、概念

1、項(xiàng)目

一個(gè)賬號有唯一的項(xiàng)目,所有虛擬機(jī)都在project里面建。

2、計(jì)算引擎

虛擬機(jī)資源。

?

二、創(chuàng)建方式

1、頁面控制臺

2、gcloud命令行

3、REST API

4、SDK

?

三、Java SDK

1、創(chuàng)建API服務(wù)憑據(jù),并下載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、計(jì)算引擎會話

public static Compute getCompute() {String appName = "your app name";String serviceAccountId = "your service account id";String proxyHost = "my.proxy.com";String proxyPort = "8090";//國內(nèi)需要代理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、創(chuàng)建虛擬機(jī)

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<>();//系統(tǒng)盤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);//數(shù)據(jù)盤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("創(chuàng)建失敗");} 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、刪除虛擬機(jī)

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、查詢虛擬機(jī)

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、設(shè)置靜態(tài)公網(wǎng)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("綁定公網(wǎng)IP失敗");}}}} catch (Exception ex) {ex.printStackTrace();}}

?

四、REST API

使用OAuth 2.0訪問Google API

Compute Engine API

保留靜態(tài)外部 IP 地址

保留靜態(tài)內(nèi)部 IP 地址

資源引用(實(shí)例與實(shí)例組、實(shí)例組與負(fù)載均衡等引用關(guān)系·)

?

創(chuàng)建實(shí)例:

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

總結(jié)

以上是生活随笔為你收集整理的常用公有云接入——谷歌的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。