設定暖機要求以改善效能

在將應用程式的程式碼載入到新建立的執行個體時,您可以使用暖機要求來減少要求及回覆的延遲時間。

App Engine 經常需要將應用程式的程式碼載入至新的執行個體。載入執行個體作業可能會在發生以下情況時進行:

  • 重新部署應用程式的版本時。
  • 因要求的負載超過目前這組運作中執行個體的容量,而建立新的執行個體時。
  • 基礎架構或實體硬體進行維護及修復時。

將應用程式的程式碼載入至新的執行個體時,可能會產生載入要求。載入要求可能會讓使用者面臨的要求延遲時間增加,但可使用「暖機要求」來避免此延遲時間增加情形。暖機要求會在任何即時要求到達該執行個體前,先將您應用程式的程式碼載入至新的執行個體。

如果您的應用程式啟用了暖機要求,App Engine 會嘗試偵測應用程式何時需要新的執行個體,並發出暖機要求來初始化新的執行個體。然而,嘗試偵測的功能並非在每種情況下均能有效運作。因此,即使應用程式已啟用暖機要求,仍可能會產生載入要求。舉例來說,如果您的應用程式沒有提供流量,則向應用程式發出的第一個要求一律為載入要求,而非暖機要求。

如同其他所有向 App Engine 應用程式發出的要求,暖機要求也會計入執行個體時數。在大多數啟用暖機要求的情況下,您不會發現執行個體小時數增加,因為應用程式只會在暖機要求中初始化,而非載入要求。如果您決定執行更多工作,例如在暖機要求期間進行預先快取,則執行個體小時用量可能會增加。如果您將 min_idle_instances 設為大於 0,這些執行個體首次啟動時可能會出現暖機要求,但在該時間過後,這些執行個體仍可供使用。

啟用暖機要求

App Engine 排程器會使用暖機要求,並依據使用者提供的設定,控制執行個體的自動調整資源配置。啟用暖機要求後,App Engine 會向 /_ah/warmup 發出 GET 要求。您可以針對這個要求實作處理常式,以執行應用程式專屬的工作,例如預先快取應用程式資料。

排程器判定需要更多執行個體時,就會啟動執行個體。由於排程器會使用暖機要求啟動執行個體,因此即使停用了暖機要求,這些要求仍可能會出現在記錄檔中。

請注意,系統不保證會呼叫暖機要求,並且在某些狀況下會改為傳送載入要求,例如:該執行個體為首先啟動的執行個體,或是流量發生遽增。然而,如果暖機要求已啟用,系統會「盡可能」嘗試將要求傳送至暖機完成的執行個體。

如要啟用暖機要求,請在 app.yaml 檔案的 inbound_services 指令下方新增 warmup 元素,例如:

inbound_services:
- warmup

建立處理常式

建立處理常式,以便處理傳送至 /_ah/warmup 的要求。處理常式應執行應用程式需要的任何暖機邏輯。


// Sample warmup demonstrates usage of the /_ah/warmup handler.
package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	"cloud.google.com/go/storage"
)

var startupTime time.Time
var client *storage.Client

func main() {
	// Perform required setup steps for the application to function.
	// This assumes any returned error requires a new instance to be created.
	if err := setup(context.Background()); err != nil {
		log.Fatalf("setup: %v", err)
	}

	// Log when an appengine warmup request is used to create the new instance.
	// Warmup steps are taken in setup for consistency with "cold start" instances.
	http.HandleFunc("/_ah/warmup", func(w http.ResponseWriter, r *http.Request) {
		log.Println("warmup done")
	})
	http.HandleFunc("/", indexHandler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
		log.Printf("Defaulting to port %s", port)
	}

	log.Printf("Listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

// setup executes per-instance one-time warmup and initialization actions.
func setup(ctx context.Context) error {
	// Store the startup time of the server.
	startupTime = time.Now()

	// Initialize a Google Cloud Storage client.
	var err error
	if client, err = storage.NewClient(ctx); err != nil {
		return err
	}

	return nil
}

// indexHandler responds to requests with our greeting.
func indexHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}
	uptime := time.Since(startupTime).Seconds()
	fmt.Fprintf(w, "Hello, World! Uptime: %.2fs\n", uptime)
}