Small problems encountered during go-micro installation and use MAC

brew install automake
brew install libtool
brew install protobuf

#go mod模式下进行安装
go install google.golang.org/protobuf/cmd/protoc-gen-go
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc
go install github.com/asim/go-micro/cmd/protoc-gen-micro/v3@latest

test:

syntax = "proto3";
package user;
option go_package ="./userpb";
message UserReq {
  int64 user_id = 1;
  string user_name = 2;
  string password = 3;
}

message UserResp{
  string reply=1;
}

service Hello{
  rpc GetUser(UserReq) returns (UserResp) {};
}

Generate a pb file under the user file path:

protoc --micro_out=. user.proto --go_out=. user.proto --go-grpc_out=require_unimplemented_servers=false:. user.proto

Server:

package main

import (
	"context"
	"fmt"
	"github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/registry"
	"time"
	"user/userpb"
)

type Hello struct{}

func (c *Hello) GetUser(ctx context.Context, in *userpb.UserReq, out *userpb.UserResp) (err error) {
	out.Reply = fmt.Sprintf("getUser:%d,%s,%s", in.UserId, in.UserName, in.Password)
	fmt.Println(out.Reply)
	return nil
}

func main() {
	var service micro.Service
	var options = []micro.Option{
		micro.Registry(consul.NewRegistry(func(op *registry.Options) {
			op.Addrs = []string{
				"127.0.0.1:8500",
			}
		})),
		micro.Name("test.hello"),
		micro.RegisterTTL(time.Second * 30),
		micro.RegisterInterval(time.Second * 10),
	}
	options = append(options, micro.Address("127.0.0.1:10001"))
	service = micro.NewService(options...)

	service.Init()

	// Register handler
	err := userpb.RegisterHelloHandler(service.Server(), new(Hello))
	if err != nil {
		panic(err)
	}

	// Run the server
	if err := service.Run(); err != nil {
		panic(err)
	}
}

client:

package main

import (
	"context"
	"fmt"
	"github.com/asim/go-micro/plugins/registry/consul/v3"
	"github.com/asim/go-micro/v3"
	"github.com/asim/go-micro/v3/registry"
	"user/userpb"
)

func main() {
	consulRegistry := consul.NewRegistry(func(op *registry.Options) {
		op.Addrs = []string{
			"127.0.0.1:8500",
		}
	})
	service := micro.NewService(
		micro.Registry(consulRegistry),
		micro.Address("127.0.0.1:10002"),
	)
	service.Init()

	c := userpb.NewHelloService("test.hello", service.Client())
	user, err := c.GetUser(context.Background(), &userpb.UserReq{
		UserName: "windy",
		UserId:   150,
		Password: "hhhhhhh",
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(user.Reply)
}

After starting the server, open the client to see:

In the consul management interface: 

 

 question:

If the warehouse does not exist or the path is wrong, consider modifying goproxy, which is usually a pull problem;

The type required by the pb file is inconsistent with the type that the code can give, and it is considered to be a problem with the installed version;

おすすめ

転載: blog.csdn.net/qq_37575994/article/details/127120364