소프트웨어 기술(스타트업 위주)
redis
redis 정리 입니다. 추가적인 자세한 설명 및 툴 이용 방법은 각 목차별로 공식문서 페이지로 하이퍼링크 참조하겠습니다.
1. Introduction
1.1 What is Redis?
Redis(Remote Dictionary Server)는 오픈소스 인메모리 데이터 구조 저장소로, 데이터베이스, 캐시, 메시지 브로커로 사용할 수 있습니다. Redis는 문자열, 해시, 리스트, 집합, 정렬된 집합 등 다양한 데이터 구조를 지원합니다.
주요 특징:
- 인메모리 데이터 저장으로 빠른 성능
- 다양한 데이터 타입 지원
- 영속성(Persistence) 지원
- 복제(Replication) 및 클러스터링 지원
1.2 Why use Redis?
Redis를 사용하는 이유는 다음과 같습니다:
- 고성능: 인메모리 저장으로 매우 빠른 읽기/쓰기 성능
- 유연한 데이터 구조: 다양한 데이터 타입으로 복잡한 작업 수행 가능
- 확장성: 마스터-슬레이브 복제 및 클러스터링 지원
- 영속성: 메모리 데이터를 디스크에 저장하여 데이터 손실 방지
1.3 Redis vs Other Databases
항목 | Redis | MySQL | MongoDB |
---|---|---|---|
저장 방식 | 인메모리 | 디스크 기반 | 디스크 기반 |
데이터 모델 | Key-Value | 관계형 | 문서형 |
성능 | 매우 빠름 | 보통 | 빠름 |
영속성 | 선택적 | 기본 | 기본 |
확장성 | 수평 확장 | 수직 확장 | 수평 확장 |
2. Installation & Setup
2.1 Linux 설치
Ubuntu/Debian:
sudo apt update
sudo apt install redis-server
sudo systemctl start redis-server
sudo systemctl enable redis-server
CentOS/RHEL:
sudo yum install epel-release
sudo yum install redis
sudo systemctl start redis
sudo systemctl enable redis
2.2 Docker를 이용한 설치
# Redis 컨테이너 실행
docker run -d --name redis-server -p 6379:6379 redis:latest
# Redis CLI로 접속
docker exec -it redis-server redis-cli
2.3 설정 파일 (redis.conf)
주요 설정 옵션:
# 포트 설정
port 6379
# 바인드 주소
bind 127.0.0.1
# 최대 메모리 설정
maxmemory 1gb
maxmemory-policy allkeys-lru
# 영속성 설정
save 900 1
save 300 10
save 60 10000
3. Redis Data Types
3.1 Strings
가장 기본적인 데이터 타입으로 텍스트나 바이너리 데이터를 저장합니다.
# 문자열 저장
SET mykey "Hello Redis"
# 문자열 조회
GET mykey
# 숫자 증가
SET counter 0
INCR counter
INCRBY counter 5
3.2 Lists
순서가 있는 문자열 리스트입니다.
# 리스트에 요소 추가
LPUSH mylist "first"
RPUSH mylist "second"
RPUSH mylist "third"
# 리스트 조회
LRANGE mylist 0 -1
# 리스트에서 요소 제거
LPOP mylist
RPOP mylist
3.3 Sets
중복되지 않는 문자열 집합입니다.
# 집합에 요소 추가
SADD myset "apple"
SADD myset "banana"
SADD myset "cherry"
# 집합 조회
SMEMBERS myset
# 집합 연산
SADD set1 "a" "b" "c"
SADD set2 "b" "c" "d"
SINTER set1 set2 # 교집합
SUNION set1 set2 # 합집합
3.4 Hashes
필드-값 쌍의 해시 테이블입니다.
# 해시 설정
HSET user:1 name "John"
HSET user:1 email "john@example.com"
HSET user:1 age 30
# 해시 조회
HGET user:1 name
HGETALL user:1
# 다중 설정
HMSET user:2 name "Jane" email "jane@example.com" age 25
3.5 Sorted Sets
점수에 따라 정렬된 중복되지 않는 문자열 집합입니다.
# 정렬된 집합에 요소 추가
ZADD leaderboard 100 "player1"
ZADD leaderboard 150 "player2"
ZADD leaderboard 200 "player3"
# 순위별 조회
ZRANGE leaderboard 0 -1
ZRANGE leaderboard 0 -1 WITHSCORES
# 점수별 조회
ZRANGEBYSCORE leaderboard 100 200
4. Basic Commands
4.1 Key Management
# 키 존재 확인
EXISTS mykey
# 키 삭제
DEL mykey
# 키 만료 시간 설정
EXPIRE mykey 60 # 60초 후 만료
TTL mykey # 남은 시간 확인
# 키 이름 변경
RENAME oldkey newkey
# 모든 키 조회 (주의: 운영 환경에서 사용 금지)
KEYS *
4.2 Database Commands
# 데이터베이스 선택 (0-15)
SELECT 1
# 현재 데이터베이스의 모든 키 삭제
FLUSHDB
# 모든 데이터베이스의 키 삭제
FLUSHALL
# 데이터베이스 정보
INFO
4.3 Server Commands
# Redis 서버 정보
INFO server
# 메모리 사용량
INFO memory
# 클라이언트 목록
CLIENT LIST
# 설정 확인
CONFIG GET maxmemory
# 설정 변경
CONFIG SET maxmemory 2gb
5. Data Persistence
5.1 RDB (Redis Database)
특정 시점의 데이터 스냅샷을 디스크에 저장합니다.
# redis.conf 설정
save 900 1 # 900초 동안 1개 이상 키 변경시 저장
save 300 10 # 300초 동안 10개 이상 키 변경시 저장
save 60 10000 # 60초 동안 10000개 이상 키 변경시 저장
# 수동 저장
SAVE # 동기 저장 (블로킹)
BGSAVE # 비동기 저장 (백그라운드)
5.2 AOF (Append Only File)
모든 쓰기 명령을 로그 파일에 기록합니다.
# AOF 활성화
appendonly yes
# AOF 파일명
appendfilename "appendonly.aof"
# 동기화 정책
appendfsync everysec # 1초마다 (권장)
# appendfsync always # 매 명령마다
# appendfsync no # OS에 위임
5.3 RDB vs AOF
항목 | RDB | AOF |
---|---|---|
파일 크기 | 작음 | 큼 |
복구 속도 | 빠름 | 느림 |
데이터 손실 | 일부 가능 | 최소 |
성능 영향 | 낮음 | 높음 |
6. Replication
6.1 Master-Slave 설정
마스터 서버 (redis.conf):
bind 0.0.0.0
port 6379
슬레이브 서버 (redis.conf):
replicaof 192.168.1.100 6379
replica-read-only yes
6.2 복제 명령어
# 슬레이브로 설정
REPLICAOF 192.168.1.100 6379
# 복제 중단
REPLICAOF NO ONE
# 복제 정보 확인
INFO replication
7. Clustering
7.1 Redis Cluster 설정
최소 3개의 마스터 노드가 필요합니다.
# 클러스터 모드로 Redis 시작
redis-server --cluster-enabled yes --cluster-config-file nodes.conf --port 7000
# 클러스터 생성
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 --cluster-replicas 0
7.2 클러스터 관리
# 클러스터 정보
CLUSTER INFO
CLUSTER NODES
# 노드 추가
redis-cli --cluster add-node 127.0.0.1:7003 127.0.0.1:7000
# 슬롯 재분배
redis-cli --cluster reshard 127.0.0.1:7000
8. Performance & Monitoring
8.1 성능 튜닝
# 메모리 최적화
maxmemory-policy allkeys-lru
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
# 네트워크 최적화
tcp-keepalive 60
tcp-backlog 511
# 디스크 I/O 최적화
stop-writes-on-bgsave-error no
8.2 모니터링
# 실시간 명령어 모니터링
MONITOR
# 느린 쿼리 로그
SLOWLOG GET 10
# 메모리 사용량 분석
MEMORY USAGE mykey
MEMORY STATS
8.3 Redis 클라이언트 연결
# 연결된 클라이언트 수
INFO clients
# 특정 클라이언트 연결 해제
CLIENT KILL 127.0.0.1:12345
9. Use Cases & Applications
9.1 캐싱
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
# 캐시 저장
r.setex('user:1', 3600, 'user_data') # 1시간 TTL
# 캐시 조회
cached_data = r.get('user:1')
9.2 세션 저장소
# 세션 저장
session_id = "sess_123456"
session_data = {"user_id": 1, "username": "john"}
r.hmset(f"session:{session_id}", session_data)
r.expire(f"session:{session_id}", 1800) # 30분 TTL
9.3 실시간 리더보드
# 점수 추가/업데이트
r.zadd("game_leaderboard", {"player1": 1500, "player2": 1200})
# 상위 10명 조회
top_players = r.zrevrange("game_leaderboard", 0, 9, withscores=True)
9.4 메시지 큐 (Pub/Sub)
# 발행자 (Publisher)
r.publish("news_channel", "Breaking news!")
# 구독자 (Subscriber)
pubsub = r.pubsub()
pubsub.subscribe("news_channel")
for message in pubsub.listen():
if message['type'] == 'message':
print(f"Received: {message['data']}")
10. Security
10.1 인증 설정
# redis.conf
requirepass mypassword
# 사용자별 권한 설정 (Redis 6.0+)
user default on nopass ~* &* -@all
user john on >mypassword ~cached:* +@read
10.2 네트워크 보안
# 특정 IP만 허용
bind 127.0.0.1 192.168.1.0/24
# 포트 변경
port 16379
# 위험한 명령어 비활성화
rename-command FLUSHDB ""
rename-command FLUSHALL ""
rename-command CONFIG "CONFIG_9a8b7c6d"
10.3 SSL/TLS 설정
# TLS 활성화 (Redis 6.0+)
tls-port 6380
tls-cert-file /path/to/redis.crt
tls-key-file /path/to/redis.key
tls-ca-cert-file /path/to/ca.crt
참고 자료: