接入步骤
- 添加SkyWalking Go依赖。
package main
import (
"context"
"flag"
"fmt"
"github.com/SkyAPM/go2sky"
httpPlugin "github.com/SkyAPM/go2sky/plugins/http"
"github.com/SkyAPM/go2sky/reporter"
"io/ioutil"
"log"
"net/http"
"time"
)
- 查看接入点信息。
应用列表的接入指引会根据您所在资源池提供v3版本接入点(Skywalking 8.*)的ENDPOINT(天翼云vpc网络接入点)、鉴权TOKEN信息。
- 初始化SkyWalking Go SDK。
注意需将token和endpoint替换成相应地域的接入点信息。
使用gRPC协议上报数据。
serverPort := flag.String("port", "9891", "server port")
token := flag.String("token", "<token>", "token") // 鉴权信息
endpoint := flag.String("endpoint", "<endpoint>", "endpoint") // grpc端口
authMap := map[string]string{
"x-ctg-authorization": *token,
}
flag.Parse()
report, err := reporter.NewGRPCReporter(*endpoint, reporter.WithAuthHeader(authMap))
//report, err := reporter.NewLogReporter()
tracer, err := go2sky.NewTracer(service,
go2sky.WithReporter(report), go2sky.WithInstance("client_addr")) //填写您的客户端地址
- client端上报例子。
func do(tracer *go2sky.Tracer, serverPort string, client *http.Client) {
for {
time.Sleep(5*time.Second)
doClient(tracer, client, "client", "http://localhost:" + serverPort + "/helloserver")
}
}
func doClient(tracer *go2sky.Tracer, client *http.Client, spanName string, url string) {
clientReq, err1 := http.NewRequest(http.MethodGet, url, nil)
parentSpan, newCtx, _ := tracer.CreateLocalSpan(context.Background())
parentSpan.SetOperationName(spanName)
defer parentSpan.End()
clientReq = clientReq.WithContext(newCtx)
res, err1 := client.Do(clientReq)
if err1 != nil {
fmt.Println(err1, "send req error")
return
}
defer res.Body.Close()
body, err1 := ioutil.ReadAll(res.Body)
fmt.Println(string(body))
}
- 服务端上报例子。
route := http.NewServeMux()
route.HandleFunc("/helloserver", func(writer http.ResponseWriter, request *http.Request) {
upstreamURL := "http://localhost:9891/hello1"
client, err := httpPlugin.NewClient(tracer)
clientReq, err1 := http.NewRequest(http.MethodGet, upstreamURL, nil)
if err1 != nil {
writer.WriteHeader(http.StatusInternalServerError)
log.Printf("unable to create http request error: %v \n", err)
return
}
subSpan, newCtx, _ := tracer.CreateLocalSpan(request.Context())
subSpan.SetOperationName("server2")
defer subSpan.End()
clientReq = clientReq.WithContext(newCtx)
res, err1 := client.Do(clientReq)
if err1 != nil {
writer.WriteHeader(http.StatusInternalServerError)
log.Printf("unable to do http request error: %v \n", err)
return
}
defer res.Body.Close()
body, err1 := ioutil.ReadAll(res.Body)
if err1 != nil {
writer.WriteHeader(http.StatusInternalServerError)
log.Printf("read http response error: %v \n", err)
return
}
writer.WriteHeader(res.StatusCode)
_, _ = writer.Write(body)
})
sm, err := httpPlugin.NewServerMiddleware(tracer)
if err != nil {
log.Fatalf("create server middleware error %v \n", err)
}
err = http.ListenAndServe(":" + *serverPort, sm(route))
if err != nil {
log.Fatal(err)
}
- 通过以上步骤,最后就在APM控制台的应用列表页面选择目标应用,查看监控数据。