| 1 |
import asyncio |
| 2 |
import logging |
| 3 |
|
| 4 |
from aiocache import Cache |
| 5 |
from aiocache.lock import RedLock |
| 6 |
|
| 7 |
|
| 8 |
logger = logging.getLogger(__name__) |
| 9 |
cache = Cache(Cache.REDIS, endpoint='127.0.0.1', port=6379, namespace='main') |
| 10 |
|
| 11 |
|
| 12 |
async def expensive_function(): |
| 13 |
logger.warning('Expensive is being executed...') |
| 14 |
await asyncio.sleep(1) |
| 15 |
return 'result' |
| 16 |
|
| 17 |
|
| 18 |
async def my_view(): |
| 19 |
|
| 20 |
async with RedLock(cache, 'key', lease=2): # Wait at most 2 seconds |
| 21 |
result = await cache.get('key') |
| 22 |
if result is not None: |
| 23 |
logger.info('Found the value in the cache hurray!') |
| 24 |
return result |
| 25 |
|
| 26 |
result = await expensive_function() |
| 27 |
await cache.set('key', result) |
| 28 |
return result |
| 29 |
|
| 30 |
|
| 31 |
async def concurrent(): |
| 32 |
await asyncio.gather(my_view(), my_view(), my_view()) |
| 33 |
|
| 34 |
|
| 35 |
async def test_redis(): |
| 36 |
await concurrent() |
| 37 |
await cache.delete("key") |
| 38 |
await cache.close() |
| 39 |
|
| 40 |
|
| 41 |
if __name__ == '__main__': |
| 42 |
asyncio.run(test_redis()) |