Channels with Redis not working #3604
-
Hi, I struggle a bit with getting channels to run with redis and I don't really understand why. When I run the code below with
I suspect there is something fishy with the Python redis client, which is why I added the weird I really hope that I havent overlooked something...... I'm running:
from dataclasses import dataclass
from redis import Redis
from litestar import Litestar, get, post
from litestar.channels import ChannelsPlugin
from litestar.channels.backends.memory import MemoryChannelsBackend
from litestar.channels.backends.redis import RedisChannelsPubSubBackend
from litestar.response import ServerSentEvent
@dataclass
class Message:
content: str
@get("/test-redis")
async def redis_check(channels: ChannelsPlugin) -> None:
channels._backend: RedisChannelsPubSubBackend
print(channels._backend._pub_sub)
print(channels._backend._pub_sub.ping())
channels._backend._pub_sub.execute_command("PUBLISH hello world")
if channels._backend._pub_sub is not None:
await channels._backend._pub_sub.subscribe("example")
@post("/msg/{topic:str}")
async def message(topic: str, data: Message, channels: ChannelsPlugin) -> None:
channels.publish(data=data.content, channels=[topic])
# await channels.wait_published(data=data.content, channels=[topic])
@get("/msg/{topic:str}")
async def listener(topic: str, channels: ChannelsPlugin) -> ServerSentEvent:
async def generator():
async with channels.start_subscription([topic]) as subscriber:
async for event in subscriber.iter_events():
yield event
return ServerSentEvent(generator())
redis = Redis(host="localhost", port=6379)
print(redis.ping())
backend = RedisChannelsPubSubBackend(redis=redis)
app = Litestar(
route_handlers=[
redis_check,
message,
listener
],
plugins=[
ChannelsPlugin(
backend=backend,
arbitrary_channels_allowed=True
)
],
debug=True
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You're using the sync |
Beta Was this translation helpful? Give feedback.
You're using the sync
redis.Redis
. You need to useredis.asyncio.Redis
.