redigo icon indicating copy to clipboard operation
redigo copied to clipboard

How to scan struct with nested fields?

Open hellodudu opened this issue 6 years ago • 6 comments

This is an example

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gomodule/redigo/redis"
)

type LiteUser struct {
	LiteUserField int32 `bson:"lite_user_field" json:"lite_user_field" redis:"lite_user_field"`
}

type UserInfo struct {
	UserID      int64       `bson:"_id" json:"_id" redis:"_id"`
	AccountID   int64       `bson:"account_id" json:"account_id" redis:"account_id"`
	GameID      int16       `bson:"game_id" json:"game_id" redis:"game_id"`
	PlayerID    int64       `bson:"player_id" json:"player_id" redis:"player_id"`
	PlayerName  string      `bson:"player_name" json:"player_name" redis:"player_name"`
	PlayerLevel int32       `bson:"player_level" json:"player_level" redis:"player_level"`
	Expire      *time.Timer `bson:"-" json:"-" redis:"-"`

	*LiteUser `bson:"inline" json:",inline" redis:"inline"`
}

var (
	RedisConnectTimeout = time.Second * 2
	RedisReadTimeout    = time.Second * 5
	RedisWriteTimeout   = time.Second * 5
)

func WorkWithRedis() {
	pool := &redis.Pool{
		MaxIdle:   80,
		MaxActive: 12000,
		Dial: func() (redis.Conn, error) {
			c, err := redis.DialTimeout("tcp", "localhost:6379", RedisConnectTimeout, RedisReadTimeout, RedisWriteTimeout)
			if err != nil {
				panic(err.Error())
			}
			return c, err
		},
	}

	u := &UserInfo{
		UserID:     1001,
		PlayerName: "dudu",
		LiteUser: &LiteUser{
			LiteUserField: 2000,
		},
	}

	conn := pool.Get()
	if conn.Err() != nil {
		log.Fatal("redis get connection from pool failed:", conn.Err())
	}

	if _, err := conn.Do("HMSET", redis.Args{}.Add(u.UserID).AddFlat(u)...); err != nil {
		fmt.Println(err)
		return
	}

	v, err := redis.Values(conn.Do("HGETALL", u.UserID))
	if err != nil {
		fmt.Println(err)
		return
	}

	var newUser UserInfo
	if err := redis.ScanStruct(v, &newUser); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("%+v\n", newUser)

}

func main() {

	//WorkWithPool()
	WorkWithRedis()

	// server exit
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
	for {
		sig := <-c
		fmt.Printf("server closing down (signal: %v)", sig)

		switch sig {
		case syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGSTOP, syscall.SIGINT:
			fmt.Println("server exit safely")
			return
		case syscall.SIGHUP:
		default:
			return
		}
	}
}

And this is result of redis-cli hgetall

➜  test redis-cli hgetall 1001
 1) "_id"
 2) "1001"
 3) "account_id"
 4) "0"
 5) "game_id"
 6) "0"
 7) "player_id"
 8) "0"
 9) "player_name"
10) "dudu"
11) "player_level"
12) "0"

The embedded field lite_user_field didn't save to redis. Is there any way to make it possible? Thank you.

hellodudu avatar Jun 02 '20 07:06 hellodudu

Finally I found some todo information in func compileStructSpec.

func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *structSpec) {
	for i := 0; i < t.NumField(); i++ {
		f := t.Field(i)
		switch {
		case f.PkgPath != "" && !f.Anonymous:
			// Ignore unexported fields.
		case f.Anonymous:
			// TODO: Handle pointers. Requires change to decoder and
			// protection against infinite recursion.
			if f.Type.Kind() == reflect.Struct {
				compileStructSpec(f.Type, depth, append(index, i), ss)
			}
	

I change *LiteUser to LiteUser, and works well. I still wondering that will pointers be supported in the future?

hellodudu avatar Jun 02 '20 09:06 hellodudu

Happy you found an solution, and to answer you question, would be happy to look at a PR to fix this.

stevenh avatar Jun 04 '20 19:06 stevenh

@hellodudu could you test https://github.com/gomodule/redigo/pull/490 please

stevenh avatar Jun 06 '20 16:06 stevenh

with pleasure.

hellodudu avatar Jun 07 '20 03:06 hellodudu

@stevenh It works fine in my case, Thanks a lot. Please feel free to close this issue : )

hellodudu avatar Jun 07 '20 05:06 hellodudu

Thanks @hellodudu thats merged now, I just need a review on https://github.com/gomodule/redigo/pull/489 so I can get that in then I'll do a new release.

stevenh avatar Jun 07 '20 13:06 stevenh