Zipkin : Golang 微服务全链路监控(二)
Golang 微服务全链路监控实现
- broker-service -> auth-service -> postgres db
- zipkin 监控:需代码入侵
一、auth-service
- 通过 context 传递 span
main.go
package main
import (
"broker-service/auth-service"
"broker-service/auth-service/data"
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/opentracing/opentracing-go"
zipkinot "github.com/openzipkin-contrib/zipkin-go-opentracing"
"github.com/openzipkin/zipkin-go"
zipkinhttp "github.com/openzipkin/zipkin-go/reporter/http"
_ "github.com/jackc/pgconn"
_ "github.com/jackc/pgx/v4"
_ "github.com/jackc/pgx/v4/stdlib"
)
const (
// Our service name.
serviceName = "auth"
// Host + port of our service.
hostPort = "localhost:8090"
// Endpoint to send Zipkin spans to.
zipkinHTTPEndpoint = "http://localhost:9411/api/v2/spans"
)
var counts int
//auth
func main() {
// set up a span reporter
reporter := zipkinhttp.NewReporter(zipkinHTTPEndpoint)
defer reporter.Close()
// create our local service endpoint
endpoint, err := zipkin.NewEndpoint(serviceName, hostPort)
if err != nil {
log.Fatalf("unable to create local endpoint: %+v\n", err)
}
// initialize our tracer
nativeTracer, err := zipkin.NewTracer(reporter, zipkin.WithLocalEndpoint(endpoint))
if err != nil {
log.Fatalf("unable to create tracer: %+v\n", err)
}
// use zipkin-go-opentracing to wrap our tracer
tracer := zipkinot.Wrap(nativeTracer)
// optionally set as Global OpenTracing tracer instance
opentracing.SetGlobalTracer(tracer)
//connect to DB
conn := connectToDB()
if conn == nil {
log.Panic("Can't connect to Postgres!")
}
// create the service implementation
service := auth.NewService(conn, data.New(conn))
// create the HTTP Server Handler for the service
handler := auth.NewHTTPHandler(tracer, service)
// start the service
fmt.Printf("Starting %s on %s\n", serviceName, hostPort)
http.ListenAndServe(hostPort, handler)
}
func openDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("pgx", dsn)
if err != nil {
return nil, err
}
err = db.Ping()
if err != nil {
return nil, err
}
return db, nil
}
func connectToDB() *sql.DB {
dsn := "host=localhost port=5432 user=postgres password=password dbname=users sslmode=disable timezone=Asia/Shanghai connect_timeout=5"
}
for {
connection, err := openDB(dsn)
if err != nil {
log.Println(dsn)
log.Println("postgres is not ready..."