coolexp / redis

Automatically exported from code.google.com/p/redis
0 stars 0 forks source link

Multi-threaded redis.py #32

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
I've modified redis.py to work in a mult-threaded environment. Do you want it?

Chas.

Original issue reported on code.google.com by eprparad...@gmail.com on 2 May 2009 at 4:18

GoogleCodeExporter commented 8 years ago
Hello, sorry for the delay, sure it will be helpful to have! Thanks

Original comment by anti...@gmail.com on 9 May 2009 at 7:12

GoogleCodeExporter commented 8 years ago
Here is a patch to make Redis work in a multi-threaded environment.

Example:
from redis import get_connection, close_open_connections
r_c = get_connection()
r_c.delete('tl')
close_open_connections()

Code (should be added to redis.py):
import threading

connections = threading.local()

def get_connection(host=None, port=None, timeout=None, db=None):
    key = '%s:%s' % (host, port)
    cur_connection = hasattr(connections, key)

    if not cur_connection:
        client = Redis(host, port, timeout, db)
        client.cache_key = key
        setattr(connections, key, client)

    return getattr(connections, key)

def close_open_connections():
    for key in dir(connections):
        if '__' not in key:
            getattr(connections, key).disconnect()
            delattr(connections, key)

Original comment by ami...@gmail.com on 9 Jun 2009 at 8:20

GoogleCodeExporter commented 8 years ago
While it certainly would allow the use of the Python redis library, each time 
you use
an operation you would create a TCP connection! That is a pretty expensive 
operation.

The approach I use and would propose is to wrap a "lock" around the redis 
library.
This way you would do:

lock.acquire()
do redis call
lock.release()

Original comment by eprparad...@gmail.com on 10 Jun 2009 at 11:35

GoogleCodeExporter commented 8 years ago

Original comment by anti...@gmail.com on 23 Oct 2009 at 12:31