猿问

如何使用 Go 连接器将 Tarantool 选择结果序列化为就绪结构

请描述一种如何将go-tarantool连接器中的选择结果序列化为 struct 以能够访问字段的方法tuple.key1.key2



芜湖不芜
浏览 96回答 1
1回答

阿晨1998

我们总是conn.*Typed()在我们的项目中使用查询来做到这一点。首先,您需要在 Tarantool 中定义表示元组的结构。然后你需要为它实现两个接口,msgpack.CustomDecoder和msgpack.CustomEncoder。你应该能够做这样的事情:type Session struct {&nbsp; &nbsp; ID&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; &nbsp; UserID&nbsp; &nbsp; &nbsp;int64&nbsp;}func (s *Session) EncodeMsgpack(e *msgpack.Encoder) error {&nbsp; &nbsp; if err := e.EncodeArrayLen(2); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; if err := e.EncodeString(s.ID); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; if err := e.EncodeInt64(s.UserID); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; return nil}func (s *Session) DecodeMsgpack(d *msgpack.Decoder) error {&nbsp; &nbsp; l, err := d.DecodeArrayLen()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; decodedFields := 1&nbsp; &nbsp; if s.ID, err = d.DecodeString(); err != nil || decodedFields == l {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; decodedFields++&nbsp; &nbsp; if s.UserID, err = d.DecodeInt64(); err != nil || decodedFields == l {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp;&nbsp; &nbsp; for i := 0; i < l-decodedFields; i++ {&nbsp; &nbsp; &nbsp; &nbsp; _ = d.Skip()&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; return nil}注意解码器。它包含计数字段。这对于非中断迁移是必要的。例如,如果 msgpack 数组的字段数少于我们尝试解码的字段数,则不会出现任何问题。选择查询的响应是 msgpack 元组的顺序数组,因此如果我们不跳过未知字段,则结构的下一个实例的解码将不会从下一个元组的开头开始。然后你可以尝试做查询:func() ([]Session, error) {&nbsp; &nbsp; const userID = 822&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; var sessions []Session&nbsp; &nbsp; err := conn.SelectTyped("session", "user", 0, 10, tarantool.IterEq, []interface{}{userID}, &resp)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return nil, err&nbsp; &nbsp; }&nbsp; &nbsp; if len(resp) == 0 {&nbsp; &nbsp; &nbsp; &nbsp; return nil, nil&nbsp; &nbsp; }&nbsp;&nbsp;&nbsp; &nbsp; return sessions, nil}在我看来,这是最好的方法,因为反射、类型转换和类型断言最少,如果使用不慎,可能会导致生产中的恐慌。这也是一种性能更高的方式。
随时随地看视频慕课网APP

相关分类

Go
我要回答