Compute Engine 執行個體擁有高效能的企業級記憶體,可供您執行應用程式。您可以分配部分記憶體以建立極低延遲和高總處理量的 RAM 磁碟。當應用程式預期使用檔案系統結構,但無法僅將結構資料儲存在記憶體中時,RAM 磁碟很適合。單獨的 RAM 磁碟不會提供任何儲存空間備援功能或靈活性,因此,建議將 RAM 磁碟與執行個體儲存空間選項一起使用。
RAM 磁碟會與應用程式共用執行個體記憶體。如果執行個體的記憶體不足,無法包含 RAM 磁碟與應用程式,請建立 highmem
機器類型的執行個體,例如 N2,或升級現有執行個體以新增更多記憶體。
事前準備
- 瞭解 RAM 磁碟與其他 Compute Engine 儲存空間選項之間的差異。
-
如果尚未設定,請先設定驗證機制。驗證是指驗證身分,以便存取 Google Cloud 服務和 API 的程序。如要在本機開發環境中執行程式碼或範例,您可以選取下列任一選項,向 Compute Engine 進行驗證:
Select the tab for how you plan to use the samples on this page:
Console
When you use the Google Cloud console to access Google Cloud services and APIs, you don't need to set up authentication.
gcloud
-
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
- Set a default region and zone.
REST
To use the REST API samples on this page in a local development environment, you use the credentials you provide to the gcloud CLI.
After installing the Google Cloud CLI, initialize it by running the following command:
gcloud init
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
For more information, see Authenticate for using REST in the Google Cloud authentication documentation.
-
建立 RAM 磁碟
您可以使用 tmpfs
檔案系統建立 RAM 磁碟,這個檔案系統預設包含在大多數 Linux 發行版中。
如果執行個體沒有足夠的可用記憶體,您可以選擇變更執行個體機器類型,採用具備較多記憶體的機器類型。
透過安全殼層 (SSH) 連線至您的執行個體。在這個範例中,請前往「VM instances」(VM 執行個體) 頁面,然後在要新增 RAM 磁碟的執行個體旁,按一下「SSH」按鈕。
建立 RAM 磁碟的掛接點。
$ sudo mkdir /mnt/ram-disk
建立並掛接新
tmpfs
RAM 磁碟。您必須決定符合儲存空間需求的size
屬性值,而不與應用程式競爭記憶體,或耗盡所有可用記憶體。在這個範例中,執行個體有具備 208 GB 記憶體的n1-highmem-32
機器類型,因此適合使用50g
的 RAM 磁碟大小。$ sudo mount -t tmpfs -o size=50g tmpfs /mnt/ram-disk
將 RAM 磁碟新增至
/etc/fstab
檔案,這樣在您重新啟動執行個體時,裝置可自動再次掛接:$ echo 'tmpfs /mnt/ram-disk tmpfs nodev,nosuid,noexec,nodiratime,size=50G 0 0' | sudo tee -a /etc/fstab
刪除 RAM 磁碟
您可以像其他任何磁碟區一樣卸載 tmpfs
RAM 磁碟。這樣會刪除 RAM 磁碟以及其中儲存的任何資料。在這個範例中,請移除掛接在 /mnt/ram-disk
中的 RAM 磁碟:
$ sudo umount /mnt/ram-disk
在重新啟動執行個體期間自動備份 RAM 磁碟資料
您可以在重新啟動執行個體之前,先備份 RAM 磁碟,以保留 RAM 磁碟資料,直到執行個體再次啟動為止。將資料備份到 Google Cloud Hyperdisk 磁碟區,如果 VM 的電腦類型不支援 Hyperdisk,則將資料備份到永久磁碟磁碟區。
建立並掛接 Hyperdisk 磁碟區,以做為 RAM 磁碟的備份磁碟使用。請確保磁碟足夠大,能夠包含 RAM 磁碟中的資訊。
使用
rsync
指令為執行個體建立關閉指令碼,這個指令碼可將 RAM 磁碟內容寫入備份磁碟區。在這個範例中,請使用 gcloud CLI 將shutdown-script
中繼資料新增至 RAM 磁碟掛接在/mnt/ram-disk
中且 Hyperdisk 磁碟區掛接在/mnt/ram-disk-backup
中的執行個體。gcloud compute instances add-metadata example-instance --metadata shutdown-script="#! /bin/bash rsync -a --delete --recursive --force /mnt/ram-disk/ /mnt/ram-disk-backup/ EOF"
您也可以選擇建立開機指令碼,這個指令碼可在執行個體再次啟動時將檔案還原至 RAM 磁碟。使用 gcloud CLI 將
startup-script
中繼資料新增至執行個體。gcloud compute instances add-metadata example-instance --metadata startup-script="#! /bin/bash rsync -a --recursive --force /mnt/ram-disk-backup/ /mnt/ram-disk/ EOF"