我正在使用 goredis据我所知 - 当客户端连接到 redis 服务器时有一个连接池。我不知道如何查询 redis 服务器并确保它是线程安全的。
目前我这样做:
我正在创建全局指针client
:client *goredis.Redis
然后我这样做:
go func () {
http.HandleFunc("/send_data/", trackHandler)
http.HandleFunc("/init/", initHandler)
http.ListenAndServe(":8000", nil)
} ()
所以现在我想在 trackHandler
和 initHandler
中使用 client
但我担心在执行查询时没有任何同步.有没有可能以这种方式搞砸事情。在 golang 中解决这个问题的规范方法是什么?
我也想知道这在 redis-py 中是如何工作的. 我看过这个thread :
In general, I suggest you either:
a. create a global redis client instance and have your code use that. b. create a global connection pool and pass that to various redis instances throughout your code.
Both of these accomplish the same thing. Both are threadsafe.
第一种情况是怎么做到的?
最佳答案
客户端有一个线程安全的连接池,每当你执行命令时,客户端都会尝试从池中获取连接。因此,即使客户端没有锁,它仍然是线程安全的,因此您应该可以使用全局客户端。
看这里 - Dial 函数如何创建一个新的连接池: https://github.com/xuyu/goredis/blob/master/redis.go#L432
这里是一个锁定连接池本身的例子。 https://github.com/xuyu/goredis/blob/master/redis.go#L287
关于 redis-py - 如果您不显式使用它,它会创建自己的内部连接池,因此它是线程安全的,因为在引擎盖下连接是全局池化的。基本上是一样的。
关于python - 线程安全的redis客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24552764/