装置
首先,你须要装置 rpcx:
go get -u -v github.com/smallnest/rpcx/...
这一步只会装置 rpcx 的根底性能。如果你想要应用 etcd 作为注册核心,你须要加上etcd这个标签。 (see build tags)
go get -u -v -tags "etcd" github.com/smallnest/rpcx/...
如果你想要应用 quic ,你也须要加上quic这个标签。
go get -u -v -tags "quic etcd" github.com/smallnest/rpcx/...
不便起见,我举荐你装置所有的tags,即便你当初并不需要他们:
go get -u -v -tags "reuseport quic kcp zookeeper etcd consul ping" github.com/smallnest/rpcx/...
tag:
- quic: 反对 quic 协定
- kcp: 反对 kcp 协定
- zookeeper: 反对 zookeeper 注册核心
- etcd: 反对 etcd 注册核心
- consul: 反对 consul 注册核心
- ping: 反对 网络品质负载平衡
- reuseport: 反对 reuseport
下面内容摘自:https://doc.rpcx.io/part1/qui…
简略的Service实现
实现一个 Sevice 就像写一个单纯的 Go 构造体:
import "context"
type Args struct {
A int
B int
}
type Reply struct {
C int
}
type Arith int
func (t *Arith) Mul(ctx context.Context, args *Args, reply *Reply) error {
reply.C = args.A * args.B
return nil
}
注册一个简略服务
s := server.NewServer()
s.RegisterName("Arith", new(Arith), "")
s.Serve("tcp", ":8972") // 能够启动quic(udp)/tcp/http服务
手写一个拦截器
其实是实现plugin的PostReadRequest办法
type SignPlugin struct {
}
// 拦截器
func (signPlugin *SignPlugin) PostReadRequest(ctx context.Context, req *protocol.Message, err error) error {
//fmt.Println(req.ServiceMethod)
//fmt.Println(req.ServicePath)
// 我这是应用json传输的
p := &你的构造体
err = json.Unmarshal(req.Payload, p)
// todo 你的逻辑(数据验证,数据处理等)
decodeMap := 你解决后的数据(如果不必解决,该步骤能够省略)
req.Payload = decodeMap
return err
}
把拦截器add到启动服务中
s := server.NewServer()
siginPlugin := &controller.SignPlugin{}
s.Plugins.Add(siginPlugin) // 把拦截器注册到服务中
s.RegisterName("Arith", new(Arith), "")
s.Serve("tcp", ":8972") // 能够启动quic(udp)/tcp/http服务
到此拦截器曾经实现.
上面附上client代码
option := client.DefaultOption
option.SerializeType = protocol.JSON // 传输数据格式
// #1
d := client.NewPeer2PeerDiscovery("tcp@127.0.0.1:8972", "")
// #2
xclient := client.NewXClient("Arith", client.Failtry, client.RandomSelect, d,option)
defer xclient.Close()
// #3
args := &example.Args{
A: 10,
B: 20,
}
// #4
reply := &example.Reply{}
// #5
err := xclient.Call(context.Background(), "Mul", args, reply)
if err != nil {
log.Fatalf("failed to call: %v", err)
}
log.Printf("%d * %d = %d", args.A, args.B, reply.C)
应用quic(UDP)和TLS证书留神:
go run -tags quic main.go
// 加载tls证书,应用quic必要步骤
cert, err := tls.LoadX509KeyPair("公钥门路", "私钥门路")
if err != nil {
panic("加载证书失败:" + err.Error())
}
configs := &tls.Config{Certificates: []tls.Certificate{cert}}
s = server.NewServer(server.WithTLSConfig(configs))
conf := &tls.Config{
InsecureSkipVerify: true, // true=跳过tls证书验证
}
option := client.DefaultOption
option.SerializeType = protocol.JSON // 传输数据格式
option.TLSConfig = conf // 应用tls证书
d := client.NewPeer2PeerDiscovery("tcp@127.0.0.1:8972", "")
xclient := client.NewXClient("Arith", client.Failtry, client.RandomSelect, d,option)