一種軟件體系結構模式,用於將大型單塊應用程序分解爲更小、可管理的獨立服務,這些服務經過語言無關協議進行通訊,每一個服務的重點作好一件事前端
微服務的概念並不新鮮,這是對服務導向架構的從新構想,但其方法更總體地與unix進程和管道保持一致。linux
微服務架構的理念:git
好處:github
Micro解決了構建微服務系統的關鍵要求。它採用微服務架構模式並將其轉換爲一組工具,由如下功能組成:golang
go-micro提供了分佈式系統開發的核心要求,包括RPC和事件驅動的通訊。web
主要功能。json
安裝go語言環境,並開啓go module功能,能夠設置 GOPROXY=https://goproxy.io 環境變量能夠永久加速下載包。在環境變量path添加一行配置 %GOPATH%bin這樣能夠在 go get 的時候安裝的軟件能夠直接使用,不須要切換路徑,GOPATH:是工做空間目錄後端
臨時加速,只在當前控制檯有效:api
1,下載proto,選擇本身須要的版本解壓放在 %GOPATH%bin下,方便管理:服務器
https://github.com/protocolbuffers/protobuf/releases
2,安裝protoc-gen-go:
go get -u github.com/golang/protobuf/protoc-gen-go
3,安裝micro:
go get github.com/micro/micro
go mod init module名:用於建立go module項目module名:建議和父文件夾的名字相同
在桌面新建文件夾 demo
自定義一個文件夾:打開cmd
進入桌面上的demo
後,運行 go mod init demo,
運行完後新建handler,proto/hello文件夾,以及main.go文件
目錄結構定義爲:
demo -handler -proto --hello main.go go.mod
在proto/hello下新建 hello.proto文件,內容以下
syntax = "proto3"; // 定義protobuf版本 //定義接口 service Hello { rpc Say (SayRequest) returns (SayResponse); //定義接口方法 } // SayRequest,SayResponse:能夠爲不一樣接口定義輸入輸出參數 message SayRequest { string name = 1; } message SayResponse { string msg = 1; }
打開cmd
進入proto/hello下 編譯proto文件:
protoc --micro_out=. --go_out=. hello/hello.proto
而後就會產生兩個文件,hello.micro.go,hello.pb.go
在handler下,新建hello_handler.go文件
package handler import ( "context" pb "demo/proto/hello"//proto文件的路徑 ) type hello struct{} func NewHelloApi() pb.HelloHandler { return &hello{} } func (self *hello) Say(ctx context.Context, req *pb.SayRequest, resp *pb.SayResponse) error { resp.Msg = "hello " + req.Name return nil }
編寫main:
package main import ( "fmt" "github.com/micro/go-micro" "log" "demo/handler" hello_api "demo/proto/hello" ) const ( ServiceName = "demo.api" ) func main() { service := micro.NewService( micro.Name(ServiceName), micro.Version("1.0.0"), ) service.Init() //掛載服務 err := hello_api.RegisterHelloHandler(service.Server(), handler.NewHelloApi()) if err != nil { fmt.Println(err) } // 啓動api服務 if err := service.Run(); err != nil { log.Fatal(err) } }
更新依賴:
go mod tidy
運行:
go run main.go
使用 micro提供的工具
micro call demo.api Hello.Say '{"name":"John"}'
使用 postman
運行 網關:
micro api --namespace=demo
測試接口
運行網關的時候:添加namespace這個參數,該參數值( demo)和 ServiceName(demo.api)的前綴必需要一致,然後面的字符就是訪問該服務的前綴 ,例如:api ,因此經過網關訪問就是:http://127.0.0.1:8080/api/hello/say,
hello:是定義的接口,
say:是該接口提供的方法