入門Go Micro

 go-mrcro 是一個可插入RPC分佈式系統開發的框架。它支持{json,proto}-rpc的編碼方式.可以使用consul 或者其餘方式的服務發現,默認是用consul.提供隨機散列的負載均衡.
git


目錄結構

client.gogithub

service.gojson

proto/greeter.protobash


建立一個greeter.proto

syntax = "proto3";

service Greeter {
	rpc Hello(HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
	string name = 1;
}

message HelloResponse {
	string greeting = 2;
}複製代碼

cd proto 進入到proto文件啊下,執行:
負載均衡

protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. greeter.proto複製代碼

生成greeter.micro.go , greeter.pb.go框架


服務發現

裝好consul分佈式

brew install consul
ui

運行consul
編碼

consul agent -dev -advertise=127.0.0.1
spa


若是您想使用etcd代替consul ,導入插件並在二進制文件中設置命令行標誌。

import ( _ "github.com/micro/go-plugins/registry/etcd" )

service --registry=etcd --registry_address=127.0.0.1:2379


簡單服務 service.go

package main

import (
	"context"
	"fmt"

	micro "github.com/micro/go-micro"
	proto "github.com/micro/examples/service/proto"
)

type Greeter struct{}

func (g *Greeter) Hello(ctx context.Context, req *proto.HelloRequest, rsp *proto.HelloResponse) error {
	rsp.Greeting = "Hello " + req.Name
	return nil
}

func main() {
	// Create a new service. Optionally include some options here.
	service := micro.NewService(
		micro.Name("greeter"),
	)

	// Init will parse the command line flags.
	service.Init()

	// Register handler
	proto.RegisterGreeterHandler(service.Server(), new(Greeter))

	// Run the server
	if err := service.Run(); err != nil {
		fmt.Println(err)
	}
}複製代碼



簡單客戶端: client.go

package main

import (
	"context"
	"fmt"

	micro "github.com/micro/go-micro"
	proto "github.com/micro/examples/service/proto"
)


func main() {
	// Create a new service. Optionally include some options here.
	service := micro.NewService(micro.Name("greeter.client"))
	service.Init()

	// Create new greeter client
	greeter := proto.NewGreeterService("greeter", service.Client())

	// Create new greeter 
        clientgreeter := proto.NewGreeterService("greeter", service.Client())
        ticker := time.NewTicker(time.Second)
        for{   
              // Call the greeter   
            rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{Name: "lizhongxuan !!!"})   
            if err != nil {      
                fmt.Println(err)   
                }   
            // Print response   
            fmt.Println(rsp.Greeting)   
            <- ticker.C
        }

	// Print response
	fmt.Println(rsp.Greeting)
}複製代碼

運行

go run client.go複製代碼


能夠修更名字,運行多個試試,看下負載均衡.當一個服務都沒有的時候,會panic.

相關文章
相關標籤/搜索