kratos微服務框架學習筆記一(kratos-demo)

来源:https://www.cnblogs.com/ailumiyana/archive/2019/12/18/12061432.html
-Advertisement-
Play Games

[toc] kratos微服務框架學習筆記一(kratos demo) 今年大部分時間飄過去了,沒怎麼更博和github,現在開發任務也差不多完成了,會比較輕鬆,考慮到今後發展,打算看看微服務框架。 常見微服務框架主要有這麼幾個 , a microservice toolkit from The N ...


目錄


kratos微服務框架學習筆記一(kratos-demo)

今年大部分時間飄過去了,沒怎麼更博和github,現在開發任務也差不多完成了,會比較輕鬆,考慮到今後發展,打算看看微服務框架。


常見微服務框架主要有這麼幾個

gizmo, a microservice toolkit from The New York Times ★
go-micro, a microservices client/server library ★
gotalk, async peer communication protocol & library
Kite, a micro-service framework
gocircuit, dynamic cloud orchestration
Kratos,bilibili開源的一套Go微服務框架,包含大量微服務相關框架及工具。

這裡有一篇關於kit,go-mirco,gizmo,Kite的比較:

Go 微服務框架對比:Go Micro, Go Kit, Gizmo, Kite

我打算最先看看的框架是kratos,也不為什麼,因為喜歡b站(#^.^#)。

github上關於kratos的介紹:

名字來源於:《戰神》游戲以希臘神話為背景,講述由凡人成為戰神的奎托斯(Kratos)成為戰神並展開弒神屠殺的冒險歷程。

目標
致力於提供完整的微服務研發體驗,整合相關框架及工具後,微服務治理相關部分可對整體業務開發周期無感,從而更加聚焦於業務交付。對每位開發者而言,整套Kratos框架也是不錯的學習倉庫,可以瞭解和參考到bilibili在微服務方面的技術積累和經驗。

Features
HTTP Blademaster:核心基於gin進行模塊化設計,簡單易用、核心足夠輕量;
GRPC Warden:基於官方gRPC開發,集成discovery服務發現,並融合P2C負載均衡;
Cache:優雅的介面化設計,非常方便的緩存序列化,推薦結合代理模式overlord;
Database:集成MySQL/HBase/TiDB,添加熔斷保護和統計支持,可快速發現數據層壓力;
Config:方便易用的paladin sdk,可配合遠程配置中心,實現配置版本管理和更新;
Log:類似zap的field實現高性能日誌庫,並結合log-agent實現遠程日誌管理;
Trace:基於opentracing,集成了全鏈路trace支持(gRPC/HTTP/MySQL/Redis/Memcached);
Kratos Tool:工具鏈,可快速生成標準項目,或者通過Protobuf生成代碼,非常便捷使用gRPC、HTTP、swagger文檔;

kratos本體

先拉代碼


如果下不動可以試試配置下代理

記得打開 go111module

kratos本體

類似於go命令,可以執行各種子工具,如go buildgo tool : kratos buildkratos run

C:\server\src\test-src\Go_Test\kratos>kratos -h
NAME:
   kratos - kratos工具集

USAGE:
   kratos [global options] command [command options] [arguments...]

VERSION:
   0.3.1

COMMANDS:
   new, n        創建新項目
   build, b      kratos build
   run, r        kratos run
   tool, t       kratos tool
   version, v    kratos version
   self-upgrade  kratos self-upgrade
   help, h       Shows a list of commands or help for one command

GLOBAL OPTIONS:
   --help, -h     show help
   --version, -v  print the version

C:\server\src\test-src\Go_Test\kratos>kratos version
 Version:      0.3.1
 Go version:   go1.13.5
 Built:        2019/11/06
 OS/Arch:      windows/amd64

demo

Quick start

Requirments
Go version>=1.13

Installation

GO111MODULE=on && go get -u github.com/bilibili/kratos/tool/kratos
cd $GOPATH/src
kratos new kratos-demo
通過 kratos new 會快速生成基於kratos庫的腳手架代碼,如生成 kratos-demo

Build & Run

cd kratos-demo/cmd
go build
./cmd -conf ../configs
打開瀏覽器訪問:http://localhost:8000/kratos-demo/start,你會看到輸出了Golang 大法好 !!!

官方介紹的有點簡潔,咱們動手一步步來:

先進入$GOPATH/src 目錄

kratos new demo

C:\server\src\go\src>kratos new demo
go get -u github.com/bilibili/kratos/tool/kratos-gen-project
go: finding golang.org/x/sys latest
go: finding golang.org/x/crypto latest
genproject: 安裝成功!
go: finding github.com/bilibili/kratos master
go: downloading github.com/bilibili/kratos v0.3.2-0.20191216053608-e8e05452b3b0
go: downloading google.golang.org/grpc v1.24.0
go: extracting google.golang.org/grpc v1.24.0
go: extracting github.com/bilibili/kratos v0.3.2-0.20191216053608-e8e05452b3b0
go: downloading golang.org/x/net v0.0.0-20191011234655-491137f69257
go: extracting golang.org/x/net v0.0.0-20191011234655-491137f69257
go: downloading github.com/prometheus/client_golang v1.1.0
go: downloading github.com/go-sql-driver/mysql v1.4.1
go: downloading github.com/fsnotify/fsnotify v1.4.7
go: downloading google.golang.org/genproto v0.0.0-20191009194640-548a555dbc03
go: downloading gopkg.in/go-playground/validator.v9 v9.29.1
go: downloading github.com/shirou/gopsutil v2.19.6+incompatible
go: extracting github.com/go-sql-driver/mysql v1.4.1
go: extracting github.com/prometheus/client_golang v1.1.0
go: extracting gopkg.in/go-playground/validator.v9 v9.29.1
go: extracting github.com/fsnotify/fsnotify v1.4.7
go: downloading github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2
go: downloading github.com/gogo/protobuf v1.3.0
go: extracting github.com/dgryski/go-farm v0.0.0-20190423205320-6a90982ecee2
go: downloading github.com/go-playground/universal-translator v0.16.0
go: extracting github.com/go-playground/universal-translator v0.16.0
go: extracting google.golang.org/genproto v0.0.0-20191009194640-548a555dbc03
go: extracting github.com/gogo/protobuf v1.3.0
go: downloading github.com/go-playground/locales v0.12.1
go: downloading github.com/prometheus/common v0.6.0
go: downloading github.com/leodido/go-urn v1.1.0
go: extracting github.com/prometheus/common v0.6.0
go: extracting github.com/leodido/go-urn v1.1.0
go: downloading github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
go: downloading github.com/matttproud/golang_protobuf_extensions v1.0.1
go: extracting github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
go: extracting github.com/matttproud/golang_protobuf_extensions v1.0.1
go: downloading github.com/beorn7/perks v1.0.1
go: extracting github.com/go-playground/locales v0.12.1
go: extracting github.com/beorn7/perks v1.0.1
go get -u github.com/bilibili/kratos/tool/kratos-protoc
protoc: 安裝成功!
2019/12/18 15:38:39 您還沒安裝protobuf,請進行手動安裝:https://github.com/protocolbuffers/protobuf/releases
exit status 1
go get -u github.com/bilibili/kratos/tool/kratos-gen-bts
genbts: 安裝成功!
Close: 無聲明 忽略此方法
Ping: 無聲明 忽略此方法
dao.bts.go: 生成成功
go get -u github.com/bilibili/kratos/tool/kratos-gen-mc
genmc: 安裝成功!
mc.cache.go: 生成成功
go get -u github.com/google/wire/cmd/wire
go: finding github.com/google/wire v0.4.0
go: downloading github.com/google/wire v0.4.0
go: extracting github.com/google/wire v0.4.0
go: downloading golang.org/x/tools v0.0.0-20191105231337-689d0f08e67a
go: downloading github.com/google/subcommands v1.0.1
go: extracting github.com/google/subcommands v1.0.1
go: extracting golang.org/x/tools v0.0.0-20191105231337-689d0f08e67a
go: finding golang.org/x/tools latest
go: finding github.com/google/subcommands v1.0.1
go: downloading golang.org/x/tools v0.0.0-20191218040434-6f9e13bbec44
go: extracting golang.org/x/tools v0.0.0-20191218040434-6f9e13bbec44
wire: 安裝成功!
wire: C:\server\src\go\src\demo\internal\di\wire.go:17:65: DemoServer not declared by package api
wire: generate failed
exit status 1
Project: demo
OnlyGRPC: false
OnlyHTTP: false
Directory: C:\server\src\go\src\demo

項目創建成功.

其中提示了沒安裝protobuf,需要手動安裝,先不管他直接跑demo試試。

2019/12/18 15:38:39 您還沒安裝protobuf,請進行手動安裝:https://github.com/protocolbuffers/protobuf/releases

kratos run

C:\server\src\go\src\demo>kratos run
go: downloading github.com/shirou/gopsutil v2.19.6+incompatible
build command-line-arguments: cannot load github.com/shirou/gopsutil/cpu: github.com/shirou/[email protected]+incompatible: reading https://goproxy.io/github.com/shirou/gopsutil/@v/v2.19.6+incompatible.zip: 410 Gone
panic: exit status 1

goroutine 1 [running]:
main.runAction(0xc0000922c0, 0x0, 0xc000042f30)
        C:/server/src/go/pkg/mod/github.com/bilibili/[email protected]/tool/kratos/run.go:25 +0x36e
github.com/urfave/cli.HandleAction(0x603080, 0x65fda8, 0xc0000922c0, 0xc0000922c0, 0x0)
        C:/server/src/go/pkg/mod/github.com/urfave/[email protected]/app.go:523 +0xc5
github.com/urfave/cli.Command.Run(0x64c994, 0x3, 0x0, 0x0, 0xc000042de0, 0x1, 0x1, 0x650d90, 0xa, 0x0, ...)
        C:/server/src/go/pkg/mod/github.com/urfave/[email protected]/command.go:174 +0x523
github.com/urfave/cli.(*App).Run(0xc0000ea000, 0xc0000044a0, 0x2, 0x2, 0x0, 0x0)
        C:/server/src/go/pkg/mod/github.com/urfave/[email protected]/app.go:276 +0x72c
main.main()
        C:/server/src/go/pkg/mod/github.com/bilibili/[email protected]/tool/kratos/main.go:57 +0x3f7

報錯:
cannot load github.com/shirou/gopsutil

好像是不能載入gopsutil
直接一下個試試:

go get -u github.com/shirou/gopsutil

C:\server\src\go\src\demo>go get -u github.com/shirou/gopsutil
go: downloading github.com/shirou/gopsutil v2.19.11+incompatible
go: extracting github.com/shirou/gopsutil v2.19.11+incompatible

C:\server\src\go\src\demo>kratos run
go: downloading github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6
go: extracting github.com/StackExchange/wmi v0.0.0-20180116203802-5d049714c4a6
go: downloading github.com/go-ole/go-ole v1.2.4
go: extracting github.com/go-ole/go-ole v1.2.4
# demo/api
..\api\client.go:15:68: undefined: DemoClient
..\api\client.go:21:9: undefined: NewDemoClient
panic: exit status 2

可以運行了,但是沒跑起來,api路徑貌似和protobuf是有關聯的,那麼安裝個protobuf試試。

https://github.com/protocolbuffers/protobuf/releases

下載,我是windows系統在path裡面添加下bin目錄環境變數即可。

protoc
Usage: protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
  -IPATH, --proto_path=PATH   Specify the directory in which to search for
                              imports.  May be specified multiple times;
                              directories will be searched in order.  If not
                              given, the current working directory is used.
                              If not found in any of the these directories,
                              the --descriptor_set_in descriptors will be
                              checked for required proto file.
  --version                   Show version info and exit.
  -h, --help                  Show this text and exit.
  --encode=MESSAGE_TYPE       Read a text-format message of the given type
                              from standard input and write it in binary
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --decode=MESSAGE_TYPE       Read a binary message of the given type from
                              standard input and write it in text format
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --decode_raw                Read an arbitrary protocol message from
                              standard input and write the raw tag/value
                              pairs in text format to standard output.  No
                              PROTO_FILES should be given when using this
                              flag.
  --descriptor_set_in=FILES   Specifies a delimited list of FILES
                              each containing a FileDescriptorSet (a
                              protocol buffer defined in descriptor.proto).
                              The FileDescriptor for each of the PROTO_FILES
                              provided will be loaded from these
                              FileDescriptorSets. If a FileDescriptor
                              appears multiple times, the first occurrence
                              will be used.
  -oFILE,                     Writes a FileDescriptorSet (a protocol buffer,
    --descriptor_set_out=FILE defined in descriptor.proto) containing all of
                              the input files to FILE.
  --include_imports           When using --descriptor_set_out, also include
                              all dependencies of the input files in the
                              set, so that the set is self-contained.
  --include_source_info       When using --descriptor_set_out, do not strip
                              SourceCodeInfo from the FileDescriptorProto.
                              This results in vastly larger descriptors that
                              include information about the original
                              location of each decl in the source file as
                              well as surrounding comments.
  --dependency_out=FILE       Write a dependency output file in the format
                              expected by make. This writes the transitive
                              set of input file paths to FILE
  --error_format=FORMAT       Set the format in which to print errors.
                              FORMAT may be 'gcc' (the default) or 'msvs'
                              (Microsoft Visual Studio format).
  --print_free_field_numbers  Print the free field numbers of the messages
                              defined in the given proto files. Groups share
                              the same field number space with the parent
                              message. Extension ranges are counted as
                              occupied fields numbers.

  --plugin=EXECUTABLE         Specifies a plugin executable to use.
                              Normally, protoc searches the PATH for
                              plugins, but you may specify additional
                              executables not in the path using this flag.
                              Additionally, EXECUTABLE may be of the form
                              NAME=PATH, in which case the given plugin name
                              is mapped to the given executable even if
                              the executable's own name differs.
  --cpp_out=OUT_DIR           Generate C++ header and source.
  --csharp_out=OUT_DIR        Generate C# source file.
  --java_out=OUT_DIR          Generate Java source file.
  --js_out=OUT_DIR            Generate JavaScript source.
  --objc_out=OUT_DIR          Generate Objective C header and source.
  --php_out=OUT_DIR           Generate PHP source file.
  --python_out=OUT_DIR        Generate Python source file.
  --ruby_out=OUT_DIR          Generate Ruby source file.
  @<filename>                 Read options and filenames from file. If a
                              relative file path is specified, the file
                              will be searched in the working directory.
                              The --proto_path option will not affect how
                              this argument file is searched. Content of
                              the file will be expanded in the position of
                              @<filename> as in the argument list. Note
                              that shell expansion is not applied to the
                              content of the file (i.e., you cannot use
                              quotes, wildcards, escapes, commands, etc.).
                              Each line corresponds to a single argument,
                              even if it contains spaces.

確保protoc能夠執行,刪除demo目錄重新創建:

這次能夠運行成功了

先試試文檔給的路徑:

不行, 看看源碼:

blademaster應該就是對gin框架的裁剪

看看demo服務做了什麼,

// New new a bm server.
func New(s pb.DemoServer) (engine *bm.Engine, err error) {
    var (
        hc struct {
            Server *bm.ServerConfig
        }
    )
    if err = paladin.Get("http.toml").UnmarshalTOML(&hc); err != nil {
        if err != paladin.ErrNotExist {
            return
        }
        err = nil
    }
    svc = s
    engine = bm.DefaultServer(hc.Server)
    pb.RegisterDemoBMServer(engine, s)
    initRouter(engine)
    err = engine.Start()
    return
}

func initRouter(e *bm.Engine) {
    e.Ping(ping)
    g := e.Group("/abc")
    {
        g.GET("/start", howToStart)
    }
}

添加了個/abc組,註冊了/start 路由.

// Group creates a new router group. You should add all the routes that have common middlwares or the same path prefix.
// For example, all the routes that use a common middlware for authorization could be grouped.
func (group *RouterGroup) Group(relativePath string, handlers ...HandlerFunc) *RouterGroup {
    return &RouterGroup{
        Handlers: group.combineHandlers(handlers),
        basePath: group.calculateAbsolutePath(relativePath),
        engine:   group.engine,
        root:     false,
    }
}

看介紹,大概意思是創建給使用相同中間件和路徑首碼的路由使用的路由組。

試試路徑
/abc/start

成功了:


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. json文件處理 1.1 什麼是json JSON(JavaScript Object Notation,JS對象簡譜)是一種輕量級的數據交換格式。它基於ECMAScript(歐洲電腦協會制定的js規範)的一個子集,採用完全獨立於編程語言的文本格式來存儲和表示數據。簡潔和清晰的層次結構使得J ...
  • 1.26個字母大小寫成對列印,例如:Aa,Bb...... 2.一個list包含10個數字,然後生成一個新的list,要求新的list裡面的數都比之前的數多1 3.倒序取出每個單詞的第一個字母,例如:I am a good boy! 方法1 方法2 4.輸入一個自己的生日月份,用if和else判斷一 ...
  • 這次來學習一下SpringMVC的源碼. 對於常見的項目架構模式,比如大名鼎鼎的SSM(SpringMVC,Spring,Mybatis)框架. SpringMVC ->web層(Controller層) Spring ->service層 mybatis ->dao層 從SpringMVC層面上講 ...
  • 語法 傳值與傳引用 Python參數傳遞採用的是“傳對象引用”的方式。這種方式相當於傳值和傳引用的一種綜合。 如果函數收到的是一個可變對象(比如字典或者列表)的引用,就能修改對象的原始值--相當於通過“傳引用”來傳遞對象。 如果函數收到的是一個不可變對象(比如數字、字元或者元組)的引用,就不能直接修 ...
  • 爬蟲與反爬 爬蟲:自動獲取網站數據的程式,關鍵是批量的獲取。 反爬蟲:使用技術手段防止爬蟲程式的方法 誤傷:反爬技術將普通用戶識別為爬蟲,從而限制其訪問,如果誤傷過高,反爬效果再好也不能使用(例如封ip,只會限制ip在某段時間內不能訪問) 成本:反爬蟲需要的人力和機器成本 攔截:成功攔截爬蟲,一般攔 ...
  • 一、操作redis redis是一個key-value存儲系統,value的類型包括string(字元串),list(鏈表),set(集合),zset(有序集合),hash(哈希類型)。為了保證效率,數據都是緩衝在記憶體中,在處理大規模數據讀寫的場景下運用比較多。 備註:預設redis有16個資料庫, ...
  • 一、前提 多台客戶端 / 伺服器 之間傳遞實體類的序列化對象 需要實現四個類,即伺服器類,線程類,客戶端類及實體類 註:實體類需實現介面:implements Serializable 二、伺服器類 伺服器類,需要實現兩個類:ServerSocket 和 Socket 。且 ServerSocket ...
  • 詳細使用教程 1、沒安裝Python的小伙伴需要先安裝一下 2、win+r輸入cmd打開命令行,輸入:pip install baidu-aip,如下安裝百度AI的模塊。 3、新建文本文檔,copy如下代碼,然後另存為py尾碼的文檔即可,小編的命名為:test.py。 from aip import ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...