- 921. Minimum Add to Make Parentheses Valid 使括号有效的最少添加
- 915. Partition Array into Disjoint Intervals 分割数组
- 932. Beautiful Array 漂亮数组
- 940. Distinct Subsequences II 不同的子序列 II
1、 broker-service->auth-service->postgresdb;
2、 zipkin监控:需代码入侵;
1、 通过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...")
time.Sleep(2 * time.Second)
counts++
} else {
log.Println("connected to postgres")
return connection
}
if counts > 100 {
log.Panic(err)
}
}
}
1、 定义auth服务;
httpService.go
package auth
import (
"log"
"net/http"
opentracing "github.com/opentracing/opentracing-go"
"broker-service/middleware"
)
type httpService struct {
service Service
}
type RequestPayload struct {
Action string json:"action"
Auth AuthPayload json:"auth,omitempty"
Log loggerPayload json:"log,omitempty"
}
type AuthPayload struct {
Email string json:"email"
Password string json:"password"
}
type loggerPayload struct {
Name string json:"name"
Data string json:"data"
}
// authHandler is our HTTP Handlerfunc for a Auth request.
func (s *httpService) authHandler(w http.ResponseWriter, req *http.Request) {
var requestPayload AuthPayload
err := s.readJSON(w, req, &requestPayload)
if err != nil {
s.errorJSON(w, err)
return
}
log.Println("requestPayload:", requestPayload)
// call our Auth binding
result, err := s.service.Auth(req.Context(), requestPayload)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// return the result
s.writeJSON(w, http.StatusAccepted, result)
}
// NewHTTPHandler returns a new HTTP handler our svc2.
func NewHTTPHandler(tracer opentracing.Tracer, service Service) http.Handler {
// Create our HTTP Service.
svc := &httpService{
service: service}
// Create the mux.
mux := http.NewServeMux()
// Create the Auth handler.
var authHandler http.Handler
authHandler = http.HandlerFunc(svc.authHandler)
// Wrap the Auth handler with our tracing middleware.
authHandler = middleware.FromHTTPRequest(tracer, "Auth")(authHandler)
// Wire up the mux.
mux.Handle("/auth/", authHandler)
// Return the mux.
return mux
}
service.go
package auth
import (
"context"
"errors"
)
// Service interface to our svc2 service.
type Service interface {
Auth(ctx context.Context, a AuthPayload) (jsonResponse, error)
}
自定义middleware.go,context 传递 Http 请求
// Package middleware provides some usable transport middleware to deal with
// propagating Zipkin traces across service boundaries.
package middleware
import (
"fmt"
"net"
"net/http"
"strconv"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
)
// RequestFunc is a middleware function for outgoing HTTP requests.
type RequestFunc func(req *http.Request) *http.Request
// ToHTTPRequest returns a RequestFunc that injects an OpenTracing Span found in
// context into the HTTP Headers. If no such Span can be found, the RequestFunc
// is a noop.
func ToHTTPRequest(tracer opentracing.Tracer) RequestFunc {
return func(req *http.Request) *http.Request {
// Retrieve the Span from context.
if span := opentracing.SpanFromContext(req.Context()); span != nil {
// We are going to use this span in a client request, so mark as such.
ext.SpanKindRPCClient.Set(span)
// Add some standard OpenTracing tags, useful in an HTTP request.
ext.HTTPMethod.Set(span, req.Method)
span.SetTag("http.host", req.URL.Host)
span.SetTag("http.path", req.URL.Path)
ext.HTTPUrl.Set(
span,
fmt.Sprintf("%s://%s%s", req.URL.Scheme, req.URL.Host, req.URL.Path),
)
// Add information on the peer service we're about to contact.
if host, portString, err := net.SplitHostPort(req.URL.Host); err == nil {
ext.PeerHostname.Set(span, host)
if port, err := strconv.Atoi(portString); err != nil {
ext.PeerPort.Set(span, uint16(port))
}
} else {
ext.PeerHostname.Set(span, req.URL.Host)
}
// Inject the Span context into the outgoing HTTP Request.
if err := tracer.Inject(
span.Context(),
opentracing.TextMap,
opentracing.HTTPHeadersCarrier(req.Header),
); err != nil {
fmt.Printf("error encountered while trying to inject span: %+v\n", err)
}
}
return req
}
}
// HandlerFunc is a middleware function for incoming HTTP requests.
type HandlerFunc func(next http.Handler) http.Handler
// FromHTTPRequest returns a Middleware HandlerFunc that tries to join with an
// OpenTracing trace found in the HTTP request headers and starts a new Span
// called operationName. If no trace could be found in the HTTP request
// headers, the Span will be a trace root. The Span is incorporated in the
// HTTP Context object and can be retrieved with
// opentracing.SpanFromContext(ctx).
func FromHTTPRequest(tracer opentracing.Tracer, operationName string,
) HandlerFunc {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
// Try to join to a trace propagated in req.
wireContext, err := tracer.Extract(
opentracing.TextMap,
opentracing.HTTPHeadersCarrier(req.Header),
)
if err != nil {
fmt.Printf("error encountered while trying to extract span: %+v\n", err)
}
// create span
span := tracer.StartSpan(operationName, ext.RPCServerOption(wireContext))
defer span.Finish()
// store span in context
ctx := opentracing.ContextWithSpan(req.Context(), span)
// update request context to include our new span
req = req.WithContext(ctx)
// next middleware or actual request handler
next.ServeHTTP(w, req)
})
}
}
处理实现验证服务
package auth
import (
"broker-service/auth-service/data"
"context"
"database/sql"
"fmt"
"log"
"github.com/opentracing/opentracing-go"
)
// Auth is our actual service implementation.
type auth struct {
DB *sql.DB
Models data.Models
}
// NewService returns a new implementation of our Service.
func NewService(db *sql.DB, models data.Models) Service {
return &auth{
DB: db,
Models: models,
}
}
// Auth implements our Service interface.
func (auth *auth) Auth(ctx context.Context, a AuthPayload) (jsonResponse, error) {
var jsonResp jsonResponse
jsonResp.Error = true
jsonResp.Message = "Auth fialed"
// Pull span from context.
span := opentracing.SpanFromContext(ctx)
// Example binary annotations.
span.SetTag("service", "auth")
span.SetTag("AuthPayload", a)
user, err := auth.Models.User.GetByEmail(span, a.Email)
if err != nil {
log.Println("get user failed from db: ", err)
span.SetTag("error", err.Error())
return jsonResp, err
}
log.Println("user:", user)
valid, err := user.PasswordMatches(a.Password)
if err != nil || !valid {
log.Println("invalid user: ", err)
span.SetTag("error", err.Error())
return jsonResp, err
}
jsonResp = jsonResponse{
Error: false,
Message: fmt.Sprintf("Logged in user %s", user.Email),
Data: user,
}
log.Println("auth response: ", jsonResp)
return jsonResp, nil
}
通过client 向服务发送验证请求(由 broker-service 调用)
package auth
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"broker-service/middleware"
opentracing "github.com/opentracing/opentracing-go"
)
// client is our actual client implementation
type client struct {
baseURL string
httpClient *http.Client
tracer opentracing.Tracer
traceRequest middleware.RequestFunc
}
// Auth implements our Service interface.
func (c *client) Auth(ctx context.Context, a AuthPayload) (data jsonResponse, err error) {
// create new span using span found in context as parent (if none is found,
// our span becomes the trace root).
span, ctx := opentracing.StartSpanFromContext(ctx, "Auth")
defer span.Finish()
log.Println("auth: ", a)
jsonData, _ := json.Marshal(a)
url := fmt.Sprintf("%s/auth/", c.baseURL)
var payload jsonResponse
payload.Error = true
payload.Message = "Authenticatioin failed!"
// create the HTTP request
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
if err != nil {
span.SetTag("error", err.Error())
return payload, err
}
// use our middleware to propagate our trace
req = c.traceRequest(req.WithContext(ctx))
// execute the HTTP request
resp, err := c.httpClient.Do(req)
if err != nil {
// annotate our span with the error condition
span.SetTag("error", err.Error())
return
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusAccepted {
err = json.NewDecoder(resp.Body).Decode(&data)
log.Println("result: ", data)
if err != nil {
span.SetTag("error", err.Error())
return
}
if data.Error {
span.SetTag("error", data.Error)
return
}
return data, nil
}
return
}
// NewHTTPClient returns a new client instance to our auth using the HTTP
// transport.
func NewHTTPClient(tracer opentracing.Tracer, baseURL string) Service {
return &client{
baseURL: baseURL,
httpClient: &http.Client{
},
tracer: tracer,
traceRequest: middleware.ToHTTPRequest(tracer),
}
}
我已经在 ubuntu 14.0 上成功安装了 Zabbix 3.2 服务器主机上的 Z 是绿色的。不幸的是,JMX 是红色的。 Zabbix 服务器:192.168.1.112 带有 tomcat
我想制作一个仪表板,显示我们的 Azure 服务总线队列的状态,并显示“添加到队列的消息”、“队列长度”和“已处理的消息”等的历史记录。使用 Azure 管理门户,我可以看到,这些统计信息大部分是手动
我的 MYSQL 每天晚上都有事件,但我不太确定发生了什么,因为即使我将其设置得早于其他事件,它仍然在早上运行。 问题是,我如何检查运行事件的历史记录或日志,哪一个晚上锁了,哪一个是跑了没跑? 谢谢
1、监控log文件大小超过10g的server 和db 复制代码代码如下: create procedure db_sendmail_mssqllogsize as&n
本教程讨论如何使用 AspectJ 开源框架监控 Spring 应用程序在方法执行方面的性能。 传统上,监控每个 Java 方法所花费的时间的最简单方法是在方法的开头和结尾包含一些跟踪行: publi
有什么可以帮助 msmq 监控的吗?当消息出现在队列中并且在休假时相同时,我想获得一些事件/监视器。 最佳答案 查看 Windows 管理性能计数器。 如果您查看管理工具并找到“性能计数器”,您将能够
我的 Tomcat 中的一个巨大的 web 应用程序有时会开始使用过多的 DBCP 连接,从而导致问题。 为了进行调查,我想在每个时间点准确地知道什么线程/方法持有池的连接。不需要是实时的,事后分析就
在浏览器的整个页面生命周期中监视 cookie 并在 cookie 更改时触发事件的最佳 JS 或 JQuery 特定方法是什么? 最佳答案 据我所知,不可能将 change (或类似)事件直接绑定(
我想尽可能详细地报告我的笔记本的执行情况。简而言之,我想实时查看我的笔记本正在执行的每个操作。例如,我的一个函数有一个 sleep 周期为 5 秒的循环,我希望看到程序实际上正在 sleep 并且循环
Azure 容器服务是否与 Azure Monitor 集成?想知道对 kubernetes 集群进行日志记录/监控的最佳方法是什么? 最佳答案 如果您正在 Azure 上寻找监视工具,您可能需要使用
我一直在尝试使用 erlang:monitor/2 来监视 gen_server。不幸的是,每次我尝试这个时,Erlang shell 都会进入无限循环。 这是我为测试这一点而编写的测试程序。 -mo
Azure 容器服务是否与 Azure Monitor 集成?想知道对 kubernetes 集群进行日志记录/监控的最佳方法是什么? 最佳答案 如果您正在 Azure 上寻找监视工具,您可能需要使用
我想使用 编写一个 shell 脚本来监控集群中的消费者滞后 bin/kafka-run-class.sh kafka.tools.ConsumerOffsetChecker --zkconnect
在 .NET 中,假设 thread A 锁定了一个对象。同时,线程B和线程C被阻塞,等待线程A解锁对象。 现在,线程 A 解锁了对象。接下来将选择哪个线程(B 或 C)?它是如何确定的? 最佳答案
我搜索过这个主题,但发现很少有有用的细节。有了这些细节,我尝试编写一些代码如下。 注意:在将此帖子标记为重复之前,请将此帖子中共享的详细信息与其他帖子进行比较,而不仅仅是按主题。 - (NSArray
目录 1、指标监控 2、常用的监控端点 3、定制EndPoint 4、spring boot admin(可以使用)
我们使用 Prometheus 和 Grafana 来监控我们的 Kafka 集群。 在我们的应用程序中,我们使用 Kafka 流,Kafka 流有可能因异常而停止。我们正在记录事件 setUnCau
我正在建立一个复杂的网络仿真,并试图捕捉一些重要的性能测量。 我在服务器上运行了 mininet,并且我将视频从一个 mininet 主机流式传输到另一个(使用 -nodisp 选项,因为我没有 GU
Jenkins 的 openstack-plugin 使用 openstack4j 与 openstack 云对话。我正在寻找一种方法,我们可以从客户端的角度监控 openstack4j 所做的 ht
我正在处理一项需要监控 Thunderbolt 端口连接变化的要求。 (当连接或断开 Thunderbolt 电缆时)。 我尝试使用 IOServiceMatching(kIOUSBInterface
我是一名优秀的程序员,十分优秀!