QUEUE
Redis는 큐(queue) 자료 구조를 쉽게 구현할 수 있는 기능을 제공합니다.
일반적으로 Redis 큐는 리스트(list) 자료형을 사용하며,
비동기 메시징을 생산자(producer)와 소비자(consumer)정의하여 사용할 수 있습니다.
LPUSH, RPOP, LRANGE
# 한글 데이터를 보기 위해 --raw 옵션으로 cli 접속
redis-cli --raw
# 순서대로 데이터 push
LPUSH my_list '태스크1'
LPUSH my_list '태스크2'
LPUSH my_list '태스크3'
# list 타입인 key생성 확인
keys *
>> "my_list"
# list 타입의 데이터 확인
LRANGE my_list 0 -1
>>>
태스크3
태스크2
태스크1
# 데이터 pop
RPOP my_list
>>> 태스크1
# 가장 처음 push된 '태스크1'이 pop된 것을 확인
LRANGE my_list 0 -1
>>>
태스크3
태스크2
# Blocking Queue는 메시지 대기열이 비어 있을 경우 일정 시간 동안 대기하는 기능을 제공
# 아래 예시는 10초 대기 후에 nil(none)을 반환합니다.
# 0으로 인자를 주면 무기한 대기합니다.
BRPOP my_queue 10
Python 예제
import redis
import time
# Redis 연결
redis_client = redis.Redis(host='localhost', port=6379, db=1, decode_responses=True)
### Producer ###
# 큐에 메시지 추가
queue_name = 'my_queue'
messages = ['메세지1', '메세지2', '메세지3']
for message in messages:
redis_client.lpush(queue_name, message) # 큐의 끝에 메시지 추가
print(f'Produced: {message}')
### Consumer ###
while True:
message = redis_client.rpop(queue_name) # 큐의 앞에서 메시지 가져오기
if message:
print(f'Consumed: {message}')
else:
print('Queue is empty. Waiting for messages...')
time.sleep(2) # 대기 후 재시도
참조 : https://redis.io/glossary/redis-queue/
Redis Queue - Redis
Explore the comprehensive guide to Redis Queues, covering basics to advanced concepts, usage in distributed systems, and implementation in Python and Node.js.
redis.io
'Storage > Redis' 카테고리의 다른 글
Redis - 동기 vs 비동기 명령어 (0) | 2025.02.22 |
---|---|
Redis - 입문 (0) | 2024.10.03 |