0
点赞
收藏
分享

微信扫一扫

gomicro使用etcd

蓝哆啦呀 2022-06-20 阅读 82

proto

syntax = "proto3";

service Greeter {
rpc Hello(HelloRequest) returns (HelloResponse) {}
}
message HelloRequest {
string name = 1;
}

message HelloResponse {
string greeting = 2;
}

编译命令

protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. gmp.proto

client

package main

import (
proto "awesomeProjects/gmp"
"context"
"fmt"
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/etcd"
"strings"
"time"
)

func main() {
// Create a new service
options := make([]micro.Option, 0)
options = append(options,
micro.Registry(etcd.NewRegistry(func(op *registry.Options) {
op.Addrs = strings.Split("0.0.0.0:12379,0.0.0.0:32379,0.0.0.0:22379", ",")
op.Timeout = time.Second * 5
})))
service := micro.NewService(options...)
// Initialise the client and parse command line flags
service.Init()

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

// Call the greeter
rsp, err := greeter.Hello(context.TODO(), &proto.HelloRequest{Name: "John"})
if err != nil {
fmt.Println(err)
}

// Print response
fmt.Println(rsp.Greeting)
}

server

package main

import (
proto "awesomeProjects/gmp"
"context"
"fmt"
micro "github.com/micro/go-micro"
"github.com/micro/go-micro/registry"
"github.com/micro/go-micro/registry/etcd"
_ "github.com/micro/go-plugins/registry/consul"
"time"
)

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.Registry(etcd.NewRegistry(func(op *registry.Options) {
op.Addrs = []string{"0.0.0.0:12379","0.0.0.0:32379","0.0.0.0:22379"}
op.Timeout = time.Second * 5
})),
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)
}
}


举报

相关推荐

0 条评论