wredis 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- wredis/__init__.py +0 -0
- wredis/bitmap/__init__.py +1 -0
- wredis/bitmap/bitmap.py +143 -0
- wredis/hash/__init__.py +1 -0
- wredis/hash/hash.py +216 -0
- wredis/pubsub/__init__.py +1 -0
- wredis/pubsub/pupsub.py +175 -0
- wredis/queue/__init__.py +1 -0
- wredis/queue/queue.py +205 -0
- wredis/sets/__init__.py +1 -0
- wredis/sets/sets.py +158 -0
- wredis/sortedset/__init__.py +1 -0
- wredis/sortedset/sortedset.py +287 -0
- wredis/streams/__init__.py +1 -0
- wredis/streams/streams.py +220 -0
- wredis-0.1.0.dist-info/LICENSE +21 -0
- wredis-0.1.0.dist-info/METADATA +61 -0
- wredis-0.1.0.dist-info/RECORD +20 -0
- wredis-0.1.0.dist-info/WHEEL +5 -0
- wredis-0.1.0.dist-info/top_level.txt +1 -0
wredis/__init__.py
ADDED
|
File without changes
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .bitmap import RedisBitmapManager
|
wredis/bitmap/bitmap.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import redis
|
|
2
|
+
from loguru import logger
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class RedisBitmapManager:
|
|
6
|
+
"""
|
|
7
|
+
Manages Redis bitmap operations, including setting, retrieving, and counting bits,
|
|
8
|
+
as well as managing TTL (Time-to-Live) for bitmap keys.
|
|
9
|
+
|
|
10
|
+
Attributes:
|
|
11
|
+
redis_client (redis.StrictRedis): Redis client instance.
|
|
12
|
+
verbose (bool): Enables detailed logging if True.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
def __init__(
|
|
16
|
+
self,
|
|
17
|
+
host: str = "localhost",
|
|
18
|
+
port: int = 6379,
|
|
19
|
+
db: int = 0,
|
|
20
|
+
verbose: bool = True,
|
|
21
|
+
):
|
|
22
|
+
"""
|
|
23
|
+
Initializes the RedisBitmapManager with connection details.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
host (str): Hostname of the Redis server.
|
|
27
|
+
port (int): Port number of the Redis server.
|
|
28
|
+
db (int): Redis database index.
|
|
29
|
+
verbose (bool): Enable detailed logging if True.
|
|
30
|
+
"""
|
|
31
|
+
self.redis_client = redis.StrictRedis(host=host, port=port, db=db)
|
|
32
|
+
self.verbose = verbose
|
|
33
|
+
|
|
34
|
+
def log(self, message: str, level: str = "info") -> None:
|
|
35
|
+
"""
|
|
36
|
+
Logs a message if verbose mode is enabled.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
message (str): The message to log.
|
|
40
|
+
level (str): The log level (e.g., "info", "warning", "error").
|
|
41
|
+
"""
|
|
42
|
+
if self.verbose:
|
|
43
|
+
getattr(logger, level)(message)
|
|
44
|
+
|
|
45
|
+
def set_bit(self, key: str, offset: int, value: int, ttl: int = -1) -> None:
|
|
46
|
+
"""
|
|
47
|
+
Sets a bit at a specific position in a bitmap and optionally sets a TTL.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
key (str): The Redis key for the bitmap.
|
|
51
|
+
offset (int): The position of the bit to set.
|
|
52
|
+
value (int): The value to set the bit to (0 or 1).
|
|
53
|
+
ttl (int): The time-to-live for the key in seconds. If -1, no TTL is set.
|
|
54
|
+
"""
|
|
55
|
+
try:
|
|
56
|
+
self.redis_client.setbit(key, offset, value)
|
|
57
|
+
self.log(f"Set bit in '{key}' at position {offset} to value {value}.")
|
|
58
|
+
|
|
59
|
+
if ttl > 0:
|
|
60
|
+
self.redis_client.expire(key, ttl)
|
|
61
|
+
self.log(f"Set TTL of {ttl} seconds for '{key}'.")
|
|
62
|
+
except Exception as e:
|
|
63
|
+
logger.error(f"Error setting bit in '{key}': {e}")
|
|
64
|
+
|
|
65
|
+
def get_bit(self, key: str, offset: int) -> int:
|
|
66
|
+
"""
|
|
67
|
+
Retrieves the value of a bit at a specific position in a bitmap.
|
|
68
|
+
|
|
69
|
+
Args:
|
|
70
|
+
key (str): The Redis key for the bitmap.
|
|
71
|
+
offset (int): The position of the bit to retrieve.
|
|
72
|
+
|
|
73
|
+
Returns:
|
|
74
|
+
int: The value of the bit (0 or 1).
|
|
75
|
+
"""
|
|
76
|
+
try:
|
|
77
|
+
bit_value = self.redis_client.getbit(key, offset)
|
|
78
|
+
self.log(f"Bit value in '{key}' at position {offset}: {bit_value}.")
|
|
79
|
+
return bit_value
|
|
80
|
+
except Exception as e:
|
|
81
|
+
logger.error(f"Error retrieving bit from '{key}': {e}")
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
def count_bits(self, key: str) -> int:
|
|
85
|
+
"""
|
|
86
|
+
Counts the number of bits set to 1 in a bitmap.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
key (str): The Redis key for the bitmap.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
int: The number of bits set to 1.
|
|
93
|
+
"""
|
|
94
|
+
try:
|
|
95
|
+
bit_count = self.redis_client.bitcount(key)
|
|
96
|
+
self.log(f"Number of bits set to 1 in '{key}': {bit_count}.")
|
|
97
|
+
return bit_count
|
|
98
|
+
except Exception as e:
|
|
99
|
+
logger.error(f"Error counting bits in '{key}': {e}")
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
def get_ttl(self, key: str) -> int:
|
|
103
|
+
"""
|
|
104
|
+
Retrieves the time-to-live (TTL) for a bitmap key.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
key (str): The Redis key for the bitmap.
|
|
108
|
+
|
|
109
|
+
Returns:
|
|
110
|
+
int: The TTL in seconds. -1 if no TTL is set, -2 if the key does not exist.
|
|
111
|
+
"""
|
|
112
|
+
try:
|
|
113
|
+
ttl = self.redis_client.ttl(key)
|
|
114
|
+
if ttl == -1:
|
|
115
|
+
self.log(f"The bitmap '{key}' has no TTL set.", level="warning")
|
|
116
|
+
elif ttl == -2:
|
|
117
|
+
self.log(f"The bitmap '{key}' does not exist.", level="warning")
|
|
118
|
+
else:
|
|
119
|
+
self.log(f"The TTL for bitmap '{key}' is {ttl} seconds.")
|
|
120
|
+
return ttl
|
|
121
|
+
except Exception as e:
|
|
122
|
+
logger.error(f"Error retrieving TTL for '{key}': {e}")
|
|
123
|
+
return -2
|
|
124
|
+
|
|
125
|
+
def extend_ttl(self, key: str, ttl: int) -> None:
|
|
126
|
+
"""
|
|
127
|
+
Extends or sets a new TTL for a bitmap key.
|
|
128
|
+
|
|
129
|
+
Args:
|
|
130
|
+
key (str): The Redis key for the bitmap.
|
|
131
|
+
ttl (int): The new TTL in seconds.
|
|
132
|
+
"""
|
|
133
|
+
try:
|
|
134
|
+
if self.redis_client.exists(key):
|
|
135
|
+
self.redis_client.expire(key, ttl)
|
|
136
|
+
self.log(f"Extended TTL for bitmap '{key}' to {ttl} seconds.")
|
|
137
|
+
else:
|
|
138
|
+
self.log(
|
|
139
|
+
f"Cannot set TTL because the bitmap '{key}' does not exist.",
|
|
140
|
+
level="warning",
|
|
141
|
+
)
|
|
142
|
+
except Exception as e:
|
|
143
|
+
logger.error(f"Error extending TTL for '{key}': {e}")
|
wredis/hash/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .hash import RedisHashManager
|
wredis/hash/hash.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import redis
|
|
3
|
+
from loguru import logger
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class RedisHashManager:
|
|
7
|
+
"""
|
|
8
|
+
Manages Redis hash operations, including creation, reading, updating,
|
|
9
|
+
deleting fields, and managing TTL (Time-to-Live).
|
|
10
|
+
|
|
11
|
+
Attributes:
|
|
12
|
+
redis_client (redis.StrictRedis): Redis client instance.
|
|
13
|
+
verbose (bool): Enables detailed logging if True.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __init__(
|
|
17
|
+
self,
|
|
18
|
+
host: str = "localhost",
|
|
19
|
+
port: int = 6379,
|
|
20
|
+
db: int = 0,
|
|
21
|
+
verbose: bool = True,
|
|
22
|
+
):
|
|
23
|
+
"""
|
|
24
|
+
Initializes the RedisHashManager with connection details.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
host (str): Hostname of the Redis server.
|
|
28
|
+
port (int): Port number of the Redis server.
|
|
29
|
+
db (int): Redis database index.
|
|
30
|
+
verbose (bool): Enable detailed logging if True.
|
|
31
|
+
"""
|
|
32
|
+
self.redis_client = redis.StrictRedis(host=host, port=port, db=db)
|
|
33
|
+
self.verbose = verbose
|
|
34
|
+
|
|
35
|
+
def log(self, message: str, level: str = "info") -> None:
|
|
36
|
+
"""
|
|
37
|
+
Logs a message if verbose mode is enabled.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
message (str): The message to log.
|
|
41
|
+
level (str): The log level (e.g., "info", "warning", "error").
|
|
42
|
+
"""
|
|
43
|
+
if self.verbose:
|
|
44
|
+
getattr(logger, level)(message)
|
|
45
|
+
|
|
46
|
+
def create_hash(
|
|
47
|
+
self, hash_name: str, key: str, value: dict | str, ttl: int = -1
|
|
48
|
+
) -> None:
|
|
49
|
+
"""
|
|
50
|
+
Writes a key-value pair into a Redis hash and optionally sets a TTL.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
hash_name (str): Name of the hash in Redis.
|
|
54
|
+
key (str): Key within the hash.
|
|
55
|
+
value (dict | str): Value to store, serialized to JSON if it is a dictionary.
|
|
56
|
+
ttl (int): Time-to-live for the hash in seconds. If -1, no TTL is set.
|
|
57
|
+
"""
|
|
58
|
+
try:
|
|
59
|
+
json_value = json.dumps(value) if isinstance(value, dict) else value
|
|
60
|
+
self.redis_client.hset(hash_name, key, json_value)
|
|
61
|
+
self.log(f"Written to hash '{hash_name}' -> {key}: {value}")
|
|
62
|
+
|
|
63
|
+
if ttl > 0:
|
|
64
|
+
self.redis_client.expire(hash_name, ttl)
|
|
65
|
+
self.log(f"Set TTL of {ttl} seconds for hash '{hash_name}'")
|
|
66
|
+
except Exception as e:
|
|
67
|
+
logger.error(f"Error writing to hash '{hash_name}': {e}")
|
|
68
|
+
|
|
69
|
+
def read_hash(self, hash_name: str, key: str) -> dict | str | None:
|
|
70
|
+
"""
|
|
71
|
+
Reads a key-value pair from a Redis hash.
|
|
72
|
+
|
|
73
|
+
Args:
|
|
74
|
+
hash_name (str): Name of the hash in Redis.
|
|
75
|
+
key (str): Key within the hash.
|
|
76
|
+
|
|
77
|
+
Returns:
|
|
78
|
+
dict | str | None: The value stored, deserialized from JSON if applicable, or None if not found.
|
|
79
|
+
"""
|
|
80
|
+
try:
|
|
81
|
+
json_value = self.redis_client.hget(hash_name, key)
|
|
82
|
+
if json_value:
|
|
83
|
+
json_value = json_value.decode()
|
|
84
|
+
try:
|
|
85
|
+
return json.loads(json_value)
|
|
86
|
+
except json.JSONDecodeError:
|
|
87
|
+
return json_value
|
|
88
|
+
else:
|
|
89
|
+
self.log(
|
|
90
|
+
f"Field '{key}' does not exist in hash '{hash_name}'.",
|
|
91
|
+
level="warning",
|
|
92
|
+
)
|
|
93
|
+
return None
|
|
94
|
+
except Exception as e:
|
|
95
|
+
logger.error(f"Error reading from hash '{hash_name}': {e}")
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def update_hash(self, hash_name: str, key: str, new_data: dict) -> None:
|
|
99
|
+
"""
|
|
100
|
+
Updates a key-value pair in a Redis hash. If the field does not exist, it adds it.
|
|
101
|
+
|
|
102
|
+
Args:
|
|
103
|
+
hash_name (str): Name of the hash in Redis.
|
|
104
|
+
key (str): Key within the hash.
|
|
105
|
+
new_data (dict): New data to update the field.
|
|
106
|
+
"""
|
|
107
|
+
try:
|
|
108
|
+
current_value = self.read_hash(hash_name, key)
|
|
109
|
+
|
|
110
|
+
if isinstance(current_value, dict):
|
|
111
|
+
current_value.update(new_data)
|
|
112
|
+
self.create_hash(hash_name, key, current_value)
|
|
113
|
+
self.log(
|
|
114
|
+
f"Updated field '{key}' in hash '{hash_name}': {current_value}"
|
|
115
|
+
)
|
|
116
|
+
else:
|
|
117
|
+
self.create_hash(hash_name, key, new_data)
|
|
118
|
+
self.log(f"Added new field '{key}' to hash '{hash_name}': {new_data}")
|
|
119
|
+
except Exception as e:
|
|
120
|
+
logger.error(f"Error updating field '{key}' in hash '{hash_name}': {e}")
|
|
121
|
+
|
|
122
|
+
def delete_hash_field(self, hash_name: str, key: str) -> None:
|
|
123
|
+
"""
|
|
124
|
+
Deletes a specific field from a Redis hash.
|
|
125
|
+
|
|
126
|
+
Args:
|
|
127
|
+
hash_name (str): Name of the hash in Redis.
|
|
128
|
+
key (str): Key within the hash to delete.
|
|
129
|
+
"""
|
|
130
|
+
try:
|
|
131
|
+
result = self.redis_client.hdel(hash_name, key)
|
|
132
|
+
if result:
|
|
133
|
+
self.log(f"Deleted field '{key}' from hash '{hash_name}'.")
|
|
134
|
+
else:
|
|
135
|
+
self.log(
|
|
136
|
+
f"Field '{key}' does not exist in hash '{hash_name}'.",
|
|
137
|
+
level="warning",
|
|
138
|
+
)
|
|
139
|
+
except Exception as e:
|
|
140
|
+
logger.error(f"Error deleting field '{key}' from hash '{hash_name}': {e}")
|
|
141
|
+
|
|
142
|
+
def read_all_hash(self, hash_name: str) -> dict | None:
|
|
143
|
+
"""
|
|
144
|
+
Reads all fields and values from a Redis hash.
|
|
145
|
+
|
|
146
|
+
Args:
|
|
147
|
+
hash_name (str): Name of the hash in Redis.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
dict | None: A dictionary of all fields and values, or None if the hash does not exist.
|
|
151
|
+
"""
|
|
152
|
+
try:
|
|
153
|
+
hash_data = self.redis_client.hgetall(hash_name)
|
|
154
|
+
if hash_data:
|
|
155
|
+
items = {}
|
|
156
|
+
for key, value in hash_data.items():
|
|
157
|
+
value = value.decode()
|
|
158
|
+
try:
|
|
159
|
+
value = json.loads(value)
|
|
160
|
+
except json.JSONDecodeError:
|
|
161
|
+
pass
|
|
162
|
+
items[key.decode()] = value
|
|
163
|
+
|
|
164
|
+
self.log(f"Read all fields from hash '{hash_name}': {items}")
|
|
165
|
+
return items
|
|
166
|
+
else:
|
|
167
|
+
self.log(
|
|
168
|
+
f"Hash '{hash_name}' is empty or does not exist.", level="warning"
|
|
169
|
+
)
|
|
170
|
+
return None
|
|
171
|
+
except Exception as e:
|
|
172
|
+
logger.error(f"Error reading all fields from hash '{hash_name}': {e}")
|
|
173
|
+
return None
|
|
174
|
+
|
|
175
|
+
def get_ttl(self, hash_name: str) -> int | None:
|
|
176
|
+
"""
|
|
177
|
+
Retrieves the remaining time-to-live (TTL) for a Redis hash.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
hash_name (str): Name of the hash in Redis.
|
|
181
|
+
|
|
182
|
+
Returns:
|
|
183
|
+
int | None: The remaining TTL in seconds, or None if the hash does not exist or has no TTL.
|
|
184
|
+
"""
|
|
185
|
+
try:
|
|
186
|
+
ttl = self.redis_client.ttl(hash_name)
|
|
187
|
+
if ttl == -1:
|
|
188
|
+
self.log(f"Hash '{hash_name}' has no TTL set.", level="warning")
|
|
189
|
+
elif ttl == -2:
|
|
190
|
+
self.log(f"Hash '{hash_name}' does not exist.", level="warning")
|
|
191
|
+
else:
|
|
192
|
+
self.log(f"TTL for hash '{hash_name}' is {ttl} seconds.")
|
|
193
|
+
return ttl
|
|
194
|
+
except Exception as e:
|
|
195
|
+
logger.error(f"Error retrieving TTL for hash '{hash_name}': {e}")
|
|
196
|
+
return None
|
|
197
|
+
|
|
198
|
+
def extend_ttl(self, hash_name: str, ttl: int) -> None:
|
|
199
|
+
"""
|
|
200
|
+
Extends or sets a new TTL for a Redis hash.
|
|
201
|
+
|
|
202
|
+
Args:
|
|
203
|
+
hash_name (str): Name of the hash in Redis.
|
|
204
|
+
ttl (int): New TTL in seconds.
|
|
205
|
+
"""
|
|
206
|
+
try:
|
|
207
|
+
if self.redis_client.exists(hash_name):
|
|
208
|
+
self.redis_client.expire(hash_name, ttl)
|
|
209
|
+
self.log(f"Extended TTL for hash '{hash_name}' to {ttl} seconds.")
|
|
210
|
+
else:
|
|
211
|
+
self.log(
|
|
212
|
+
f"Cannot set TTL because hash '{hash_name}' does not exist.",
|
|
213
|
+
level="warning",
|
|
214
|
+
)
|
|
215
|
+
except Exception as e:
|
|
216
|
+
logger.error(f"Error extending TTL for hash '{hash_name}': {e}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .pupsub import RedisPubSubManager
|
wredis/pubsub/pupsub.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import redis
|
|
2
|
+
from threading import Thread
|
|
3
|
+
import signal
|
|
4
|
+
import json
|
|
5
|
+
from loguru import logger
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class RedisPubSubManager:
|
|
9
|
+
"""
|
|
10
|
+
Manages Redis Pub/Sub functionality, including publishing messages and subscribing to channels.
|
|
11
|
+
|
|
12
|
+
Attributes:
|
|
13
|
+
redis_client (redis.StrictRedis): Redis client instance.
|
|
14
|
+
pubsub (redis.client.PubSub): Redis Pub/Sub instance.
|
|
15
|
+
subscribers (dict): Dictionary of channels and their associated callbacks.
|
|
16
|
+
threads (list): List of threads listening to channels.
|
|
17
|
+
verbose (bool): Enables detailed logging if True.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
host: str = "localhost",
|
|
23
|
+
port: int = 6379,
|
|
24
|
+
db: int = 0,
|
|
25
|
+
verbose: bool = True,
|
|
26
|
+
):
|
|
27
|
+
"""
|
|
28
|
+
Initializes the RedisPubSubManager with connection details.
|
|
29
|
+
|
|
30
|
+
Args:
|
|
31
|
+
host (str): Hostname of the Redis server.
|
|
32
|
+
port (int): Port number of the Redis server.
|
|
33
|
+
db (int): Redis database index.
|
|
34
|
+
verbose (bool): Enable detailed logging if True.
|
|
35
|
+
"""
|
|
36
|
+
self.redis_client = redis.StrictRedis(host=host, port=port, db=db)
|
|
37
|
+
self.pubsub = self.redis_client.pubsub()
|
|
38
|
+
self.subscribers = {}
|
|
39
|
+
self.threads = []
|
|
40
|
+
self.verbose = verbose
|
|
41
|
+
|
|
42
|
+
def log(self, message: str, level: str = "info") -> None:
|
|
43
|
+
"""
|
|
44
|
+
Logs a message if verbose mode is enabled.
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
message (str): The message to log.
|
|
48
|
+
level (str): The log level (e.g., "info", "warning", "error").
|
|
49
|
+
"""
|
|
50
|
+
if self.verbose:
|
|
51
|
+
getattr(logger, level)(message)
|
|
52
|
+
|
|
53
|
+
def publish_message(self, channel: str, message: str | dict) -> None:
|
|
54
|
+
"""
|
|
55
|
+
Publishes a message to a Redis channel. Supports both strings and JSON.
|
|
56
|
+
|
|
57
|
+
Args:
|
|
58
|
+
channel (str): The channel to publish the message to.
|
|
59
|
+
message (str | dict): The message to publish. JSON messages are serialized automatically.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ValueError: If the message is neither a string nor a dictionary.
|
|
63
|
+
"""
|
|
64
|
+
try:
|
|
65
|
+
if isinstance(message, dict):
|
|
66
|
+
message = json.dumps(message)
|
|
67
|
+
elif not isinstance(message, str):
|
|
68
|
+
raise ValueError("Message must be a string or a JSON dictionary.")
|
|
69
|
+
|
|
70
|
+
self.redis_client.publish(channel, message)
|
|
71
|
+
self.log(f"Message published to channel '{channel}': {message}")
|
|
72
|
+
except Exception as e:
|
|
73
|
+
logger.error(f"Error publishing message to channel '{channel}': {e}")
|
|
74
|
+
|
|
75
|
+
def on_message(self, channel: str):
|
|
76
|
+
"""
|
|
77
|
+
Decorator to register a callback function for a specific Redis channel.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
channel (str): The channel to subscribe to.
|
|
81
|
+
|
|
82
|
+
Returns:
|
|
83
|
+
Callable: The decorated callback function.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def decorator(callback):
|
|
87
|
+
if channel not in self.subscribers:
|
|
88
|
+
self.subscribers[channel] = callback
|
|
89
|
+
self._start_listener(channel)
|
|
90
|
+
self.log(
|
|
91
|
+
f"Subscribed to channel '{channel}' with handler '{callback.__name__}'"
|
|
92
|
+
)
|
|
93
|
+
else:
|
|
94
|
+
self.log(
|
|
95
|
+
f"Handler already registered for channel '{channel}'",
|
|
96
|
+
level="warning",
|
|
97
|
+
)
|
|
98
|
+
return callback
|
|
99
|
+
|
|
100
|
+
return decorator
|
|
101
|
+
|
|
102
|
+
def _start_listener(self, channel: str) -> None:
|
|
103
|
+
"""
|
|
104
|
+
Starts a thread to listen for messages on a specific channel and execute the associated callback.
|
|
105
|
+
|
|
106
|
+
Args:
|
|
107
|
+
channel (str): The channel to listen to.
|
|
108
|
+
"""
|
|
109
|
+
|
|
110
|
+
def listener():
|
|
111
|
+
local_pubsub = self.redis_client.pubsub()
|
|
112
|
+
local_pubsub.subscribe(channel)
|
|
113
|
+
self.log(f"Listening for messages on channel '{channel}'")
|
|
114
|
+
|
|
115
|
+
for message in local_pubsub.listen():
|
|
116
|
+
if message["type"] == "message" and channel in self.subscribers:
|
|
117
|
+
callback = self.subscribers[channel]
|
|
118
|
+
data = message["data"].decode()
|
|
119
|
+
try:
|
|
120
|
+
data = json.loads(data)
|
|
121
|
+
except json.JSONDecodeError:
|
|
122
|
+
pass
|
|
123
|
+
callback(data)
|
|
124
|
+
|
|
125
|
+
thread = Thread(target=listener)
|
|
126
|
+
thread.daemon = True
|
|
127
|
+
thread.start()
|
|
128
|
+
self.threads.append(thread)
|
|
129
|
+
|
|
130
|
+
def stop_listeners(self) -> None:
|
|
131
|
+
"""
|
|
132
|
+
Stops all listener threads.
|
|
133
|
+
"""
|
|
134
|
+
for thread in self.threads:
|
|
135
|
+
if thread.is_alive():
|
|
136
|
+
self.log("Stopping listener thread...")
|
|
137
|
+
self.threads.clear()
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# Example usage
|
|
141
|
+
if __name__ == "__main__":
|
|
142
|
+
# Create an instance of RedisPubSubManager
|
|
143
|
+
pubsub_manager = RedisPubSubManager(host="localhost", verbose=True)
|
|
144
|
+
|
|
145
|
+
# Subscribe a function to "channel_1"
|
|
146
|
+
@pubsub_manager.on_message("channel_1")
|
|
147
|
+
def handle_channel_1(message):
|
|
148
|
+
if isinstance(message, dict):
|
|
149
|
+
logger.info(f"[channel_1] Received message (JSON): {message}")
|
|
150
|
+
else:
|
|
151
|
+
logger.info(f"[channel_1] Received message (String): {message}")
|
|
152
|
+
|
|
153
|
+
# Subscribe a function to "channel_2"
|
|
154
|
+
@pubsub_manager.on_message("channel_2")
|
|
155
|
+
def handle_channel_2(message):
|
|
156
|
+
if isinstance(message, dict):
|
|
157
|
+
logger.info(f"[channel_2] Received message (JSON): {message}")
|
|
158
|
+
else:
|
|
159
|
+
logger.info(f"[channel_2] Received message (String): {message}")
|
|
160
|
+
|
|
161
|
+
# Publish test messages
|
|
162
|
+
pubsub_manager.publish_message("channel_1", "Hello from channel_1!")
|
|
163
|
+
pubsub_manager.publish_message("channel_2", {"greeting": "Hello from channel_2!"})
|
|
164
|
+
|
|
165
|
+
# Handle Ctrl+C to exit cleanly
|
|
166
|
+
def signal_handler(sig, frame):
|
|
167
|
+
logger.info("\nStopping program...")
|
|
168
|
+
pubsub_manager.stop_listeners()
|
|
169
|
+
logger.info("Program stopped.")
|
|
170
|
+
exit(0)
|
|
171
|
+
|
|
172
|
+
signal.signal(signal.SIGINT, signal_handler)
|
|
173
|
+
|
|
174
|
+
# Keep the program running without while True
|
|
175
|
+
signal.pause()
|
wredis/queue/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .queue import RedisQueueManager
|