資料結構 | 回滾莫隊淺記
阿新 • • 發佈:2022-02-27
go-kit
是一個分散式的開發工具集,在大型的組織(業務)中可以用來構建微服務。其解決了分散式系統中的大多數常見問題,因此,使用者可以將精力集中在業務邏輯上。
go-kit的架構如圖分為三層結構:Transport層,Endpoint層,Service層。
Transport
層主要負責與傳輸協議HTTP,GRPC,THRIFT等相關的邏輯;Endpoint
層主要負責request/response格式的轉換,以及公用攔截器相關的邏輯;Service
層則專注於業務邏輯,就是我們的業務類、介面等相關資訊存放。
go-kit除了經典的分層架構外,還在endpoint層提供了很多公用的攔截器,如log,metric,tracing,circuitbreaker,rate-limiter等,來保障業務系統的可用性。
go-kit demo(一)基於http訪問
目錄結構
目錄結構
UserEndPoint.go
package myEndPoints
import (
"context"
"example.com/myServices"
"github.com/go-kit/kit/endpoint"
)
//定義Request、Response格式,並可以使用裝飾器(閉包)包裝函式,以此來實現各個中介軟體巢狀
type UserRequest struct {
Id int `json:"id"`
}
type UserResponse struct {
Name string `json:"name"`
}
func MakeServerEndPointGetName(s myServices.IUserService) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
r,ok := request.(UserRequest)
if !ok{
return response,nil
}
return UserResponse{Name: s.GetName(r.Id)},nil
}
}
UserService.go
package myServices
//這裡就是我們的業務類、介面等相關資訊存放
type IUserService interface {
GetName(userId int) string
}
type UserService struct {
}
func (s UserService) GetName(uid int) string {
if uid == 10{
return "wangqiang"
}
return "xiaoqiang"
}
UserTransport.go
package myTransports
import (
"context"
"encoding/json"
"errors"
"example.com/myEndPoints"
"net/http"
"strconv"
)
//Transport層主要負責與傳輸協議HTTP,GRPC,THRIFT等相關的邏輯;
func GetNameDecodeRequest (c context.Context,r *http.Request) (interface{}, error){
id := r.URL.Query().Get("id")
if id ==""{
return nil,errors.New("無效引數")
}
intid, err := strconv.Atoi(id)
if err != nil{
return nil,errors.New("無效引數")
}
return myEndPoints.UserRequest{Id: intid},nil
}
func GetNameEncodeResponse(c context.Context,w http.ResponseWriter,res interface{}) error {
w.Header().Set("Content-Type", "application/json;charset=utf-8")
return json.NewEncoder(w).Encode(res)
}
main.go
package main
import (
"example.com/myEndPoints"
"example.com/myServices"
"example.com/myTransports"
"github.com/go-kit/kit/transport/http"
"log"
sthttp "net/http"
)
func main() {
//業務介面服務
s := myServices.UserService{}
//使用myEndPoints建立業務服務
getName := myEndPoints.MakeServerEndPointGetName(s)
//使用 kit 建立 handler
// 固定格式
// 傳入 業務服務 以及 定義的 加密解密方法
server := http.NewServer(getName, myTransports.GetNameDecodeRequest, myTransports.GetNameEncodeResponse)
//監聽服務
log.Println(sthttp.ListenAndServe(":8080", server))
}
啟動程式
image.png
image.png image.png
作者:Feng_Sir
連結:https://www.jianshu.com/p/a4f81147f9ec
來源:簡書
著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。