I'm using redigo in an application and I'm wondering how my services should interface with Redis.
Wikipedia has this to say about thread-safety:
Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.
What I interpret this to mean is that if a data-structure needs to be accessed by multiple clients (hundreds, thousands if not millions in today's micro-service world) thread-safety is the way in which we ensure that state is correctly preserved in the system regardless of which client accesses the data and when. This means resolving access priority (which client got there first), ensuring lock on mutation (only one client can write at a time) while promoting concurrency (many clients can read the data if there is no change).
From what I've gathered, a redigo client can be used by multiple "goroutines" (or threads) concurrently. That leads me to believe that a singleton implementation like I'm familiar with in Java should suffice.
I see examples, e.g., here and here, where Redis connections (pool
s) are simply created in the main
method and passed in to various redigo functions. That doesn't seem like the most robust way to get things done, although they do appear to be following the singleton pattern. (Understandably the second post is really just a quick n'dirty API.)
I would do it like this:
In the
main
function callinit
which returns a redigopool
.Create handler functions (controllers) that accept a
pool
as a param (a sort of "dirty" dependency injection).
This would (I think) ensure that only a single pool
is ever created.
Alternatively, is there any reason why I can't create a pool
(client) every time I want to access the data store? If the client is killed after the transaction is complete, is there any issue with spinning up a new pool
every time a handler receives a request?