schollz/jsonstore
GitHub: schollz/jsonstore
一个基于 Go 的简单线程安全内存 JSON 键值存储库,以文件为持久化后端,适用于不需要完整数据库的轻量级存储场景。
Stars: 136 | Forks: 9
# jsonstore :convenience_store:
[](https://godoc.org/github.com/schollz/jsonstore)
*JSONStore* 是一个 Go 库,用于实现带有持久化后端的简单线程安全内存 JSON 键值存储。它适用于那些你不需要像 [MySQL](https://www.mysql.com/) 这样的 RDBMS,或者像 [MongoDB](https://www.mongodb.com/) 这样的 NoSQL 的场合——基本上也就是你只需要一个简单的键值存储的时候。一个真正简单的键值存储。*JSONStore* 适用于那些你不需要像 [etcd](https://coreos.com/etcd/docs/latest/) 这样的分布式键值存储的时候,或者
一个远程的键值存储 [Redis](https://redis.io/),亦或是像 [Bolt](https://github.com/boltdb/bolt) 这样的本地键值存储的时候。它真的只适用于那些你仅仅需要一个 JSON 文件的场合。
## 用法
首先,使用以下命令安装该库:
```
go get -u -v github.com/schollz/jsonstore
```
然后你可以将其添加到你的程序中。查看示例,或者参阅下面的基本用法:
```
ks := new(jsonstore.JSONStore)
// set a key to any object you want
type Human struct {
Name string
Height float64
}
err := ks.Set("human:1", Human{"Dante", 5.4})
if err != nil {
panic(err)
}
// Saving will automatically gzip if .gz is provided
if err = jsonstore.Save(ks, "humans.json.gz"); err != nil {
panic(err)
}
// Load any JSON / GZipped JSON
ks2, err := jsonstore.Open("humans.json.gz")
if err != nil {
panic(err)
}
// get the data back via an interface
var human Human
err = ks2.Get("human:1", &human)
if err != nil {
panic(err)
}
fmt.Println(human.Name) // Prints 'Dante'
```
磁盘上的数据存储随后将包含:
```
$ zcat humans.json.gz
{
"human:1": "{\"Name\":\"Dante\",\"Height\":5.4}"
}
```
**JSONStore** 的实际应用:
- [schollz/urls](https://github.com/schollz/urls) - URL 缩短
# 开发
使用 Go1.8(Intel i5-4310U CPU @ 2.00GHz)与使用 Redis 和 BoltDB 作为键值存储进行的基准测试。结论是 *JSONStore* 的设置/获取速度更快(因为它仅仅是一个 map),但打开速度要慢得多(因为它是一个被读入内存的文件)。因此,如果你必须存储超过 100 万条数据,请不要使用它!
```
$ go test -bench=. tests/redis/* > redis.txt
$ go test -bench=. tests/bolt/* > bolt.txt
$ go test -bench=. > jsonstore.txt
$ benchcmp bolt.txt jsonstore.txt
benchmark old ns/op new ns/op delta
BenchmarkSet-4 5471747 1847 -99.97%
BenchmarkGet-4 2424 1479 -38.99%
BenchmarkOpen100-4 11168 148035 +1225.53%
BenchmarkOpen10000-4 10095 19722376 +195267.77%
$ benchcmp redis.txt jsonstore.txt
benchmark old ns/op new ns/op delta
BenchmarkSet-4 24717 1847 -92.53%
BenchmarkGet-4 22561 1479 -93.44%
BenchmarkOpen100-4 6221 148035 +2279.60%
BenchmarkOpen10000-4 4951 19722376 +398251.36%
```
# 许可证
MIT
标签:EVTX分析, 日志审计