grpc xservice 使用

1. 安装(此处比较简单)

dep 包管理
配置环境变量
GOPATH/bin
GO/bin
protoc 下载并配置环境变量

2. xservice 安装

a. 预备(一些需要的依赖)
mkdir -p $GOPATH/src/golang.org/x
git clone https://github.com/golang/tools.git
go get github.com/gogo/protobuf/proto
go get github.com/golang/protobuf/protoc-gen-go/
go get github.com/pkg/errors
go install -v ./...
3. 简单代码
备注:项目使用的go package 为 github.com/rongfengliang/grpcapp
下面的目录在对应的子目录

a. 项目结构
├── grpcappdemo
├── grpcdemoclient
└── grpcdemoserver

b. grpcappdemo/app.proto

syntax = "proto3";
package donutloop.xservice.example.helloworld;
option go_package = "helloworld";

service HelloWorld {
  rpc Hello(HelloReq) returns (HelloResp);
}

message HelloReq {
  string subject = 1;
}

message HelloResp {
  string text = 1;
}

c. generate code
protoc -I . app.proto --xservice_out=. --go_out=. 

d. grpcdemoclient/main.go

package main

import (
	"context"
	"fmt"
	"net/http"

	pb "github.com/rongfengliang/grpcapp/grpcappdemo"
)

func main() {
	client := pb.NewHelloWorldJSONClient("http://localhost:8080", &http.Client{})
	for i := 1; i < 100000; i++ {
		resp, err := client.Hello(context.Background(), &pb.HelloReq{Subject: "World"})
		if err == nil {
			fmt.Println(resp.Text) // prints "Hello World"
		}

e. server
        
package main

import (
	"context"
	"net/http"

	pb "github.com/rongfengliang/grpcapp/grpcappdemo"
)

// HelloWorldServer HelloWorldServer
type HelloWorldServer struct{}

// Hello Hello
func (s *HelloWorldServer) Hello(ctx context.Context, req *pb.HelloReq) (*pb.HelloResp, error) {
	return &pb.HelloResp{Text: "Hello from rongfengliang " + req.Subject}, nil
}

// Run the implementation in a local server
func main() {
	handler := pb.NewHelloWorldServer(&HelloWorldServer{}, nil)
	// You can use any mux you like - NewHelloWorldServer gives you an http.Handler.
	mux := http.NewServeMux()
	// The generated code includes a const, <ServiceName>PathPrefix, which
	// can be used to mount your service on a mux.
	mux.Handle(pb.HelloWorldPathPrefix, handler)
	http.ListenAndServe(":8080", mux)
}
4. 运行
cd grpcdemoserver
go run main.go
cd grpcdemoclient
go run main.go
5. 扩展(docker 构建集成)
参考项目对应的Dockerfile && docker-compose.yml
https://github.com/rongfengliang/grpcapp 
5. 参考资料
https://github.com/google/protobuf/releases/tag/v3.5.1
https://github.com/donutloop/xservice
https://github.com/rongfengliang/grpcapp
https://github.com/golang/dep

posted on 2018-02-27 15:30  荣锋亮  阅读(212)  评论(0编辑  收藏  举报

导航