10秒鐘,讓你的方法變為RPC服務
rpcx 一個服務治理的Go RPC框架, 擁有非常多的特性,支持跨語言的服務調用。 眾多的特性可以參考 doc.rpcx.site 。它的服務治理的特性深受阿里巴巴的Dubbo框架的啟發。
在實際的產品應用中,用戶使用兩臺服務器+8臺日志搜集服務(Client),輕松處理每天幾十億的服務調用, 除了中間一個路由器硬件閃斷, 整個系統平穩運行多半年。 相比較之前Java的實現, 服務器節省了一般。 用戶使用rpcx框架重構后的系統每月為公司節省了幾十萬港元的成本。
rpcx框架的一個設計哲學就是 簡單 。不希望用戶需要花費大量的時間在框架的學習上,并且不需要proto文件或者重復且冗余的服務配置。最少只需要10行代碼就可以創建一個服務, 如果需要額外的配置,也只需要幾十行的代碼。
雖然rpcx開發簡單,但是作為開發人員來說,如果可以更加的偷懶, 那更是極好的一件事情了,這就是 xgen 開發的目的。
這個工具可以搜尋指定的 package 下可以配置成rpcx服務的類型, 并且生成一個服務器程序,將這些服務注冊到服務器程序中。你可以指定是否需要 zookeeper 、 etcd 、 consul 作為注冊中心。
這個工具的開發參考了Go的tools的實現以及DigitalOcean公司的Fatih Arslan
開發的 gomodifytags 的實現。
首先看一下這個工具參數:
$ xgen -h
Usage of xgen:
-o string
specify the filename of the output
-pkg
process the whole package instead of just the given file
-r string
registry type. support etcd, consul, zookeeper, mdns
-tags string
build tags to add to generated file
你可以使用 xgen file1.go file2.go file3.go 搜尋指定的文件生成服務,也可以 xgen -pkg github.com/rpcx-ecosystem/rpcx-examples3/xgen 為 GOPATH 中指定的 package 生成服務。 -pkg 選項優先于程序參數。
-o 選項指定生成的程序輸出到哪個文件,如果不指定,則輸出到控制臺 Stdout 。
-r 選項指定注冊中心的類型,支持 zookeeper 、 etcd 、 consul 和 mdns 。如果不指定,則采用點對點的rpc調用方式。
-tags 選項指定生成的文件是否要加上 build conditions 。
看一個例子, rpcx-examples3/xgen 中有一個server.go文件,它定義幾個類型和方法。
package xgen
import (
"context"
"fmt"
"time"
example "github.com/rpcx-ecosystem/rpcx-examples3"
)
type Arith int
func (t *Arith) Mul(ctx context.Context, args example.Args, reply *example.Reply) error {
reply.C = args.A * args.B
return nil
}
func (t *Arith) Add(ctx context.Context, args *example.Args, reply *example.Reply) error {
reply.C = args.A + args.B
return nil
}
type Echo string
func (s *Echo) Echo(ctx context.Context, args string, reply *string) error {
*reply = fmt.Sprintf("Hello %s from %s", args, *reply)
return nil
}
type TimeS struct{}
func (s *TimeS) Time(ctx context.Context, args time.Time, reply *time.Time) error {
*reply = time.Now()
return nil
}
這三個類型 Arith 、 Echo 、 TimeS 都有符合rpcx服務的方法。
rpcx的服務的方法需要滿足下面的規則:
- 類型和參數都是exported
- 方法有三個參數,并且第一個參數是 context.Context
- 方法的第三個參數是指針類型
- 方法類型為error
現在你就可以使用 xgen 生成服務端代碼。
xgen -o cmd/main.go -r "etcd" -pkg github.com/rpcx-ecosystem/rpcx-examples3/xgen
或者
xgen -o cmd/main.go -r "etcd" ./server.go
這樣就生成了一個服務器端的代碼。
你可以運行你的服務器了: go run cmd/main.go ,就這么簡單。
來自:http://colobu.com/2018/02/13/make-your-methods-as-services-in-10-seconds/