本篇主要介绍 Knative Serving 的流量灰度,通过一个 rest-api 的例子演示如何创建不同的 Revision、如何在不同的 Revision 之间按照流量比例灰度。
部署 rest-api v1
- 代码
测试之前我们需要写一段 rest-api 的代码,并且还要能够区分不同的版本。下面我基于官方的例子进行了修改,为了使用方便去掉了 github.com/gorilla/mux
依赖,直接使用 Golang 系统包 net/http
替代。这段代码可以通过 RESOURCE 环境变量来区分不同的版本。
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"flag"
)
var resource string
func main() {
flag.Parse()
//router := mux.NewRouter().StrictSlash(true)
resource = os.Getenv("RESOURCE")
if resource == "" {
resource = "NOT SPECIFIED"
}
root := "/" + resource
path := root + "/{stockId}"
http.HandleFunc("/", Index)
http.HandleFunc(root, StockIndex)
http.HandleFunc(path, StockPrice)
if err := http.ListenAndServe(fmt.Sprintf(":%s", "8080"), nil); err != nil {
log.Fatalf("ListenAndServe error:%s ", err.Error())
}
}
func Index(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the %s app! \n", resource)
}
func StockIndex(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "%s ticker not found!, require /%s/{ticker}\n", resource, resource)
}
func StockPrice(w http.ResponseWriter, r *http.Request) {
stockId := r.URL.Query().Get("stockId")
url := url.URL{
Scheme: "https",
Host: "api.iextrading.com",
Path: "/1.0/stock/" + stockId + "/price",
}
log.Print(url)
resp, err := http.Get(url.String())
if err != nil {
fmt.Fprintf(w, "%s not found for ticker : %s \n", resource, stockId)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
fmt.Fprintf(w, "%s price for ticker %s is %s\n", resource, stockId, string(body))
}
- Dockerfile
创建一个叫做 Dockerfile 的文件,把下面这些内容复制到文件中。执行 docker build --tag registry.cn-hangzhou.aliyuncs.com/knative-sample/rest-api-go:v1 --file ./Dockerfile .
命令即可完成镜像的编译。
你在测试的时候请把 registry.cn-hangzhou.aliyuncs.com/knative-sample/rest-api-go