Created
August 11, 2017 08:57
-
-
Save nak3/d934b9cadb0d7ae4b3812e66405d42ff to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"io/ioutil" | |
"sync" | |
"github.com/dgraph-io/badger" | |
) | |
func main() { | |
opt := badger.DefaultOptions | |
dir, _ := ioutil.TempDir("", "badger") | |
opt.Dir = dir | |
opt.SyncWrites = true | |
opt.ValueDir = dir | |
kv, _ := badger.NewKV(&opt) | |
defer kv.Close() | |
wg := new(sync.WaitGroup) | |
wb := make([]*badger.Entry, 0, 100) | |
wg.Add(1) | |
// Async writes would be useful if you want to write some key-value pairs without waiting | |
// for them to be complete and perform some cleanup when they are written. | |
// In Dgraph we keep on flushing posting lists periodically to badger. We do it an async | |
// manner and provide a callback to it which can do the cleanup when the writes are done. | |
f := func(err error) { | |
defer wg.Done() | |
if err != nil { | |
// At this point you can retry writing keys or send error over a channel to handle | |
// in some other goroutine. | |
fmt.Printf("Got error: %+v\n", err) | |
} | |
// Check for error in entries which could be non-nil if the user supplies a CasCounter. | |
for _, e := range wb { | |
if e.Error != nil { | |
fmt.Printf("Got error: %+v\n", e.Error) | |
} | |
} | |
// You can do cleanup now. Like deleting keys from cache. | |
fmt.Println("All async sets complete.") | |
} | |
for i := 0; i < 100; i++ { | |
k := []byte(fmt.Sprintf("%09d", i)) | |
wb = append(wb, &badger.Entry{ | |
Key: k, | |
Value: k, | |
}) | |
} | |
kv.BatchSetAsync(wb, f) | |
fmt.Println("Finished writing keys to badger.") | |
wg.Wait() | |
for i := 0; i < 100; i++ { | |
var item badger.KVItem | |
key := []byte(fmt.Sprintf("%09d", i)) | |
if err := kv.Get(key, &item); err != nil { | |
fmt.Printf("Error while getting key: %q", key) | |
} | |
fmt.Printf("GET key: %s value: %s\n", key, item.Value()) | |
} | |
// Output: Finished writing keys to badger. | |
// All async sets complete. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment