1.介紹
1.1go-micro 簡介
⚫ Go Micro 是一個插件化的基礎框架,基於此可以構建微服務,Micro 的設計哲學是可插拔的插件化架構
⚫ 在架構之外,它默認實現了 consul 作爲服務發現(2019 年源碼修改了默認使用mdns),通過 http 進行通信,通過 protobuf 和 json 進行編解碼
1.2 go-micro 的主要功能
服務發現:
負載均衡:
消息編碼:
請求/響應:
Async Messaging:
可插拔接口:
插件地址:https://github.com/micro/go-plugins
2.實踐
2.1go-micro helloWorld
2.1.1hello.proto
syntax = "proto3";
//結構體
message InfoRequest{
string user = 1;
}
message InfoResponse {
string msg = 2;
}
//接口
service Hello {
rpc Info (InfoRequest) returns (InfoResponse){
}
}
運行如下命令,生成go代碼
protoc -I . --micro_out . --go_out . ./hello.proto
2.1.2server.go
package main
import (
"context"
"fmt"
"github.com/micro/go-micro"
"log"
pb "test/micro/proto"
)
//聲明結構體
type Hello struct{}
func (g *Hello) Info(ctx context.Context, req *pb.InfoRequest, rep *pb.InfoResponse) error{
rep.Msg = "你好" + req.Username
return nil
}
func main() {
//1.得到服務端實例
service := micro.NewService(
//設置微服務的名字,用來訪問
// micro call hello Hello.Info {"username":"zhangsan"}
micro.Name("hello"),
)
//2.初始化
service.Init()
//3.服務註冊
err := pb.RegisterHelloHandler(service.Server(),new(Hello))
if err != nil{
fmt.Println(err)
}
//4.啓動服務
if err := service.Run(); err != nil{
log.Fatal(err)
}
}
2.2go-micro 案例2
2.2.1api.proto
syntax = "proto3";
//結構體
message CallRequest{
string name = 1;
}
message CallResponse{
string message = 2;
}
service Call {
rpc CallFunc (CallRequest) returns (CallResponse){};
}
message EmptyRequest{}
message EmptyResponse{}
service Empty{
rpc EmptyFunc (EmptyRequest) returns (EmptyResponse){};
}
生成go代碼
protoc -I . --micro_out . --go_out . ./api.proto
2.2.2server.go
package main
import (
"context"
"fmt"
"github.com/go-micro"
"github.com/go-micro/errors"
"log"
pb "test/micro/proto"
)
type Call struct {
}
type Empty struct {
}
func (c *Call) CallFunc(ctx context.Context, req *pb.CallRequest, rep *pb.CallResponse) error {
log.Println("收到了Call.CallFunc請求")
if len(req.Name) == 0{
return errors.BadRequest("go.micro.api.call","no name")
}
rep.Message = "Call.CallFunc接收到了你的請求" + req.Name
return nil
}
func (c *Empty) EmptyFunc(ctx context.Context, req *pb.EmptyRequest, rep *pb.EmptyResponse) error {
log.Println("收到Empty.EmptyFunc請求")
return nil
}
func main() {
service := micro.NewService(
micro.Name("go.micro.api.call"),
)
service.Init()
err := pb.RegisterCallHandler(service.Server(), new(Call))
if err != nil{
fmt.Println(err)
}
err = pb.RegisterEmptyHandler(service.Server(), new(Empty))
if err != nil{
fmt.Println(err)
}
if err := service.Run();err != nil{
log.Fatal(err)
}
}