GolangNote

Golang笔记

bolt 使用示例

Permalink

bolt 是一款高性能的key value 数据库,下面是它的使用示例:

Go: 嵌入式数据库 boltdb 示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
package main

import (
    "encoding/binary"
    "encoding/json"
    "fmt"
    "log"
    "time"

    "github.com/boltdb/bolt"
)

type Post struct {
    Created time.Time
    Title   string
    Content string
}

type User struct {
    ID   int
    Name string
}

func main() {

    db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()

    /*

        db.Update(func(tx *bolt.Tx) error {
            b, err := tx.CreateBucketIfNotExists([]byte("posts"))
            if err != nil {
                return err
            }
            return b.Put([]byte("2015-01-01"), []byte("My New Year post"))
        })
    */

    db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("posts"))
        v := b.Get([]byte("2015-01-01"))
        fmt.Printf("%s\n", v)

        if err := b.ForEach(func(k, v []byte) error {
            fmt.Printf("A %s is %s.\n", k, v)
            return nil
        }); err != nil {
            return err
        }

        return nil
    })

    post := &Post{
        Created: time.Now(),
        Title:   "My first post",
        Content: "Hello, this is my first post.",
    }

    db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucketIfNotExists([]byte("posts"))
        if err != nil {
            return err
        }
        encoded, err := json.Marshal(post)
        if err != nil {
            return err
        }

        return b.Put([]byte(post.Created.Format(time.RFC3339)), encoded)
    })

    db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucketIfNotExists([]byte("posts"))
        if err != nil {
            return err
        }
        encoded, err := json.Marshal(post)
        if err != nil {
            return err
        }

        return b.Put([]byte(post.Created.Format(time.RFC3339)), encoded)
    })

    db.Update(func(tx *bolt.Tx) error {
        b, err := tx.CreateBucketIfNotExists([]byte("MyBucket"))
        err = b.Put([]byte("answer"), []byte("42"))
        return err
    })

    db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("MyBucket"))
        v := b.Get([]byte("answer"))
        fmt.Printf("%s\n", v)

        return nil
    })

    db.Update(func(tx *bolt.Tx) error {
        u := User{}
        // Retrieve the users bucket.
        // This should be created when the DB is first opened.
        //b := tx.Bucket([]byte("users"))
        b, err := tx.CreateBucketIfNotExists([]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)
    })

    // Delete the key in a different write transaction.
    if err := db.Update(func(tx *bolt.Tx) error {
        return tx.Bucket([]byte("MyBucket")).Delete([]byte("answer"))
    }); err != nil {
        log.Fatal(err)
    }

    db.View(func(tx *bolt.Tx) error {
        b := tx.Bucket([]byte("users"))

        if err := b.ForEach(func(k, v []byte) error {
            fmt.Printf("A %s is %s.\n", k, v)
            return nil
        }); err != nil {
            return err
        }

        return nil
    })

}

// 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
}

官方网站 https://github.com/boltdb/bolt

官方示例 https://godoc.org/github.com/boltdb/bolt#pkg-examples

本站就是使用 boltdb 作为底层数据库。

本文网址: https://golangnote.com/topic/109.html 转摘请注明来源

Related articles

golang snappy 的使用场合

google 自家的 snappy 压缩优点是非常高的速度和合理的压缩率。压缩率比 gzip 小,CPU 占用小。...

golang Selenium WebDriver 使用记录

Selenium WebDriver 直接通过浏览器自动化的本地接口来调用浏览器,以达到模拟浏览器行为的操作,如点击、选择、鼠标移动等。下面是记录个人使用golang 驱动的记录。...

Write a Comment to "bolt 使用示例"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms