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
 
 
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值