pb2tarsgo

用法

  1. go get github.com/TarsCloud/TarsGo/tars
  2. go get github.com/golang/protobuf/{proto,protoc-gen-go}
  3. install protoc
  • Add tarsrpc plugin for protoc-gen-go
  1. cd $GOPATH/src/github.com/golang/protobuf/protoc-gen-go && cp -r $GOPATH/src/github.com/TarsCloud/TarsGo/tars/tools/pb2tarsgo/protoc-gen-go/{link_tarsrpc.go, tarsrpc} .
  2. go build .
  3. cp protoc-gen-go $GOPATH/bin
  4. export PATH=$PATH:$GOPATH/bin

示例

  • proto 文件
  1. syntax = "proto3";
  2. package helloworld;
  3. // The greeting service definition.
  4. service Greeter {
  5. // Sends a greeting
  6. rpc SayHello (HelloRequest) returns (HelloReply) {}
  7. }
  8. // The request message containing the user's name.
  9. message HelloRequest {
  10. string name = 1;
  11. }
  12. // The response message containing the greetings
  13. message HelloReply {
  14. string message = 1;
  15. }
  • 生成代码
  1. protoc --go_out=plugins=tarsrpc:. helloworld.proto
  • 服务端
  1. package main
  2. import (
  3. "github.com/TarsCloud/TarsGo/tars"
  4. "helloworld"
  5. )
  6. type GreeterImp struct {
  7. }
  8. func (imp *GreeterImp) SayHello(input helloworld.HelloRequest)(output helloworld.HelloReply, err error) {
  9. output.Message = "hello" + input.GetName()
  10. return output, nil
  11. }
  12. func main() { //Init servant
  13. imp := new(GreeterImp) //New Imp
  14. app := new(helloworld.Greeter) //New init the A JCE
  15. cfg := tars.GetServerConfig() //Get Config File Object
  16. app.AddServant(imp, cfg.App+"."+cfg.Server+".GreeterTestObj") //Register Servant
  17. tars.Run()
  18. }
  • 客户端
  1. package main
  2. import (
  3. "fmt"
  4. "github.com/TarsCloud/TarsGo/tars"
  5. "helloworld"
  6. )
  7. func main() {
  8. comm := tars.NewCommunicator()
  9. obj := fmt.Sprintf("StressTest.HelloPbServer.GreeterTestObj@tcp -h 127.0.0.1 -p 10014 -t 60000")
  10. app := new(helloworld.Greeter)
  11. comm.StringToProxy(obj, app)
  12. input := helloworld.HelloRequest{Name: "sandyskies"}
  13. output, err := app.SayHello(input)
  14. if err != nil {
  15. fmt.Println("err: ", err)
  16. }
  17. fmt.Println("result is:", output.Message)
  18. }