golang boltdb tip

bolt 作者提供的思路

Be sure to check errors from `View()` and `Update()`. For example, there's a missing error check in NewList().
It's more efficient to use `binary.BigEndian.PutUint64()` instead of `fmt.Sprintf()` to represent ids. For one thing, it's much faster to encode & decode. Second of all, when you use a stringified representation then it won't insert sequentially.


// CreateUser saves u to the store. The new user ID is set on u once the data is persisted.
func (s *Store) CreateUser(u *User) error {
    return s.db.Update(func(tx *bolt.Tx) error {
        // Retrieve the users bucket.
        // This should be created when the DB is first opened.
        b := tx.Bucket([]byte("users"))

        // Generate ID for the user.
        // This returns an error only if the Tx is closed or not writeable.
        // That can't happen in an Update() call so I ignore the error check.
        id, _ := b.NextSequence()
        u.ID = int(id)

        // Marshal user data into bytes.
        buf, err := json.Marshal(u)
        if err != nil {
            return err

        // Persist bytes to users bucket.
        return b.Put(itob(u.ID), buf)

// itob returns an 8-byte big endian representation of v.
func itob(v int) []byte {
    b := make([]byte, 8)
    binary.BigEndian.PutUint64(b, uint64(v))
    return b

type User struct {
    ID int

byte to int 相互转换:

func Btoi(b []byte) int {
	s0, _ := strconv.Atoi(string(b))
	return s0

func Itob(i int) []byte {
	return []byte(strconv.Itoa(i))


func itob(v int64) []byte {
	b := make([]byte, 8)
	binary.BigEndian.PutUint64(b, uint64(v))
	return b

func btoi(v []byte) int64 {
	return int64(binary.BigEndian.Uint64(v))


timestamp := time.Unix(int64(binary.BigEndian.Uint64(v)), 0)
本文网址: https://golangnote.com/topic/166.html (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles