在Web服务器应用程序golang中使用键值存储
我试图在go Web服务器应用程序中使用一个简单的键值存储,它应该存储一些信息 问题是,我只能创建它的一个实例,因为它写入磁盘和文件夹是锁定的,所以我需要找到方法,用我的Web服务器访问键值存储 因此,每个当前实例都可以访问它(读/写)。 我该怎么做 目前,我的应用程序如下所示: 我想使用的软件包是: 基本上,我会在main之前创建一个实例,并将键值存储的实例传递给rtt函数,但这在go中似乎不可能直接实现。还是我做错了什么?全球连接实例 首先使用键值存储的单个实例创建一个包,并将该连接设置为一个包变量,您可以连接一次,然后保持打开状态以供将来使用。下面是一些伪代码示例:在Web服务器应用程序golang中使用键值存储,go,Go,我试图在go Web服务器应用程序中使用一个简单的键值存储,它应该存储一些信息 问题是,我只能创建它的一个实例,因为它写入磁盘和文件夹是锁定的,所以我需要找到方法,用我的Web服务器访问键值存储 因此,每个当前实例都可以访问它(读/写)。 我该怎么做 目前,我的应用程序如下所示: 我想使用的软件包是: 基本上,我会在main之前创建一个实例,并将键值存储的实例传递给rtt函数,但这在go中似乎不可能直接实现。还是我做错了什么?全球连接实例 首先使用键值存储的单个实例创建一个包,并将该连接设置为一
package kvstore
var conn *diskv.Conn // or whatever the type of the conn is
func Connect(...) {
// crate connection and fill conn
conn = diskv.New(...)
}
func Write(k, v []byte) error {
return conn.Write(k, v)
}
这样你就有了一个“全球”连接,可以在任何地方使用。只需调用kvstore.Write(…)
任意位置即可写入存储
同步并发访问
如果您的应用程序使用了多个可以访问kvstore的Goroutine,那么您(可能——取决于您使用的包是否已经为您执行了此操作)需要同步访问。您可以通过为连接使用互斥来实现这一点:
var (
conn *diskv.Conn // or whatever the type of the conn is
mutex sync.Mutex
)
func Write(k, v []byte) error {
// everywhere you use the conn object, lock the mutex before and unlock after
mutex.Lock()
defer mutex.Unlock()
return conn.Write(k, v)
}
您还可以使用actor模式。这里有一篇由Peter Bourgon撰写的文章,解释了这个问题。使用actor模式,我们可以确保conn对象只在一个goroutine中使用,从而不需要使用互斥
简单kvstore包实现
kvstore的示例用法
只需将其复制到两个不同的文件夹中,然后重试。它可以工作。正如我所说,我无法从任何函数之外的键值存储中定义实例,但您仍然发布了示例帖子来实现这一点。也许你可以看看github的例子。你说的是github的例子吗?我会编辑我的答案,然后把有用的代码放在那里。
package kvstore
import "github.com/peterbourgon/diskv"
var conn *diskv.Diskv
// Connect opens the global diskv db
func Connect(dir string) {
flatTransform := func(s string) []string { return []string{} }
conn = diskv.New(diskv.Options{
BasePath: dir,
Transform: flatTransform,
CacheSizeMax: 1024 * 1024,
})
}
// Write writes to the global diskv db
func Write(k string, v []byte) error {
return conn.Write(k, v)
}
// Read reads from the global diskv db
func Read(k string) ([]byte, error) {
return conn.Read(k)
}
// Erase deletes a key from the global discv db
func Erase(k string) error {
return conn.Erase(k)
}
package main
import (
"github.com/tehsphinx/diskv"
)
func main() {
// call this once in startup sequence.
kvstore.Connect("my-data-dir")
// use this anywhere to write to key value store
kvstore.Write("alpha", []byte{'1', '2', '2'})
// use this anywhere to read from kvstore
kvstore.Read("alpha")
// use this anywhere to delete from kvstore
kvstore.Erase("alpha")
}