go-micro examples 中service 代码学习(开发基于go-micro的微服务)

这是一个 创建 微服务 的例子:https://micro.mu/docs/cn/writing-a-go-service.html

目录如下:

greeter.proto 代码如下:

syntax = "proto3";

service Greeter {
    rpc Hello(Request) returns (Response) {}
}

message Request {
    string name = 1;
}

message Response {
    string greeting = 1;
}

使用protoc 生成 greeter.pb.go  ;  greeter.micro.go;

bogon:service zhaozhiliang$ cd proto

bogon:proto zhaozhiliang$ protoc --proto_path=$GOPATH/src:. --micro_out=. --go_out=. greeter.proto

main.go 代码如下:

package main

import (
	"context"
	"fmt"
	"github.com/micro/cli"
	"github.com/micro/go-micro"
	"os"
	proto "service/proto"
)

type Greeter struct {}

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

func main() {
	service := micro.NewService(
		micro.Name("greeter"),
		micro.Flags(cli.BoolFlag{
			Name : "run_client",
			Usage : "Launch the client",
		}),
	)
	service.Init(
		//添加 runtime action
		micro.Action(func(c *cli.Context) {
			if c.Bool("run_client") {
				runClient(service)
				os.Exit(0)
			}
		}),
	)

	proto.RegisterGreeterHandler(service.Server(), new(Greeter))

	if err := service.Run(); err != nil {
		fmt.Println(err)
	}
}

func runClient(service micro.Service){
	// Create new greeter client
	greeter := proto.NewGreeterService("greeter", service.Client())

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

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

cli/main.go  代码如下:

package main

import (
	"context"
	"fmt"
	"github.com/micro/go-micro"
	proto "service/proto"
)

func main() {
	service := micro.NewService(micro.Name("greeter"))
	service.Init()

	greeter := proto.NewGreeterService("greeter", service.Client())

	rsp, err := greeter.Hello(context.TODO(), &proto.Request{Name: "liang"})
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(rsp.Greeting)
}

运行:

运行服务 :
go run main.go

运行 client :

go run main.go --run_client

使用到的模块:

go.mod  内容如下:

module service

go 1.13

require (
	github.com/golang/protobuf v1.3.2
	github.com/micro/go-micro v1.18.0
)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值