I'm new to Redis and want to know if it is good practice to open a client connection for the whole time my Java app is running. This connection would be used by various functions.
Or the alternative is better: scoping each connection to the method, which would then connect, set or get data, and close the connection at the end.
Which one is the desired approach?
Thanks.
Note: I'm using the lettuce Redis Client
Like with most connections to databaseish servers you'll want to keep the connections open. Reconnection takes a lot of time and TCP packets compared to sending 1 request packet and getting 1 reply packet almost instantly back.
Managing connections is usually done by a pool implementation. In case of lettuce the docs state
lettuce provides connection pooling for Redis Standalone and Redis Sentinel-managed connections. While pooling is not necessary when using lettuce it can be handy for some certain scenarios. Lettuce connections are designed to be long-lived and feature auto-reconnection. Multiple threads can use one connection concurrently.
I would in this case not bother to create a pool. Redis is single threaded anyways & the reason why with other libraries like jedis
you'll want to use a pool is because their connections are not thread safe.
As the author of lettuce points out in the comments there are cases where you should, even must use multiple connections. Also from the same documentation linked above:
You use blocking calls such as
BLPOP
,BRPOP
, ... to not block the whole connection. Once a connection is blocked by a blocking command, it will stay in this state until Redis responds with the result
These commands don't block Redis' single thread, they wait on certain events to happen (like elements getting added to a list). You can & should therefore interact with Redis on another connection. Not doing so should only slow you down - BUT: In case you're the only client and you're planning to write the data that causes the event you can deadlock yourself if you also want to read something before writing.
You use transactions (
MULTI/EXEC
). Transactions will switch your connection in a transactional state. Other threads which share the connection would fall unintentionally into the transaction.
In this case you basically must use multiple connections because it affects the correctness of your code. You suddenly get null
values returned during transactions which do not mean that there is no value stored. And even if you don't check return values, your changes could get rolled back without you noticing.
Keeping the redis connection open is a better option. It would also not create any issues for a program that functions asynchronously if the connection is left open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With