# -*- coding: utf-8 -*-
"""
@File    : test_redis_multi.py
@Author  : Jay
@Date    : 2026/3/19 15:37
@Desc    : 测试 Redis 多 IP、多 DB、同步/异步功能
"""
import threading
import uuid

from redis_xsync import register_redis, resolve_redis


# 同步写入测试
def run_sync_test(redis, db, key_prefix="sync"):
    with redis(db=db) as r:
        r.setnx(key_prefix, str(uuid.uuid4()))
        val = r.get(f"{key_prefix}")
        print(f"[SYNC] db={db} {key_prefix} ->", val)


async def run_async_test(redis, db, key_prefix="sync"):
    async with redis(db=3) as r:
        await r.setnx(key_prefix, str(uuid.uuid4()))
        val = await r.get(f"{key_prefix}")
        print(f"[ASYNC] db={db} {key_prefix} ->", val)


if __name__ == "__main__":
    # 第一种注册方式
    cfg = {
        'host': '127.0.0.1',
        'port': 6379,
        'db': 0,
        'password': '',
        'decode_responses': True
    }
    redis1 = register_redis(label='redis_xsync', **cfg)
    register_redis(label='redis_xsync2', **cfg)

    # 第二种注册之后全局获取
    redis2 = resolve_redis(label="redis_xsync2")

    # 同步线程
    t1 = threading.Thread(target=run_sync_test, args=(redis1, 1, "t1"))
    t2 = threading.Thread(target=run_sync_test, args=(redis2, 2, "t2"))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    # 异步测试
    import asyncio


    async def main():
        await run_async_test(redis1, 1, "s1")
        await run_async_test(redis2, 2, "s2")


    asyncio.run(main())
