1. REDIS
    1. 개요
      1. 일반
      2. 단점
      3. 아키텍처
        1. 기본
        2. NHN Japan - LINE #1
        3. NHN Japna - LINE #2 - 돈이 많이 들어요
    2. 설치 및 실행 그리고 설정
      1. 설치 및 실행
      2. 설정
    3. 간단하게 사용해 보기
      1. 유니크 ID 생성
      2. 원자적으로 값을 얻고 지우기
      3. 여러개 데이타베이스 사용해보기
      4. Pipeline
      5. FIFO Queue
      6. Simple social Graph
      7. Tag생성 하고 Tag로 검색하기
      8. Pub/Sub를 사용한 비동기 통신
    4. 활용해 보기
    5. 참조

REDIS

개요

Redis는 오픈소스이며, key-value 저장소이다.
key를 이용해 "String", "Hash", "List", "Set", "Sorted Set"을 값으로 저장 한다.

일반

2.6.x 기준 이야기, 2.4.x보다 빠른 성능 + 기능, 아직 정식 Release 안됨. 현재 2.6.0-rc6(2012-09-04) 2.6.0-rc8(2012-10-15)

  • REmote DItionary Server
  • In-memory Key-value Store
  • Memcached 처럼 빠르다.
  • 가볍다
  • milliseconds 단위의 key expire
  • Persist 가능
  • Master-slave replication
  • publish/subscribe
  • 많은 클라이언트 라이브러리
  • ANSI C로 작성됨. 라이브러리 의존성 거의 없음.
  • Lua 스크립트 지원
  • major.minor.patchlevel 형식의 버전 표시. minor숫자가 짝수면 안정 버전.
  • 다양한 데이타셋(String, Hash, List, Set, Sorted Set)
  • Atomic 연산
  • 가상메모리 지원 가능
  • 메뉴얼에 친절히 써있는 시간복잡도
  • Single thread
  • 쉬운 사용성
  • Strings-as-integers
  • 성능
  • HA 자체 지원 시작, 이전에는 Heartbeat,Pacemaker등을 이용. 발표일자 기준으로 베타상태 RC8 버전부터 포함 Redis Sentinel
  • 2.4.x 부터 jemalloc 사용

단점

  • Cluster 미지원
  • 클라이언트에서 샤딩
  • In-memory store이기 때문에 확장시 비용 부담, VM기능은 In-memory의 장점인 응답성을 떨어트린다.

아키텍처

기본

NHN Japan - LINE #1

NHN Japna - LINE #2 - 돈이 많이 들어요

설치 및 실행 그리고 설정

설치 및 실행

다운로드


$ wget http://redis.googlecode.com/files/redis-2.6.0-rc6.tar.gz
$ tar xzf redis-2.4.16.tar.gz
$ cd redis-2.4.16
$ make
$ make test

실행


$ src/redis-server ./redis.conf 
[6655] 27 Aug 12:32:23.522 # Unable to set the max number of files limit to 10032 (Operation not permitted), setting the max clients configuration to 3984.
                _._                                                  
           _.-``__ ''-._                                             
      _.-``    `.  `_.  ''-._           Redis 2.5.12 (00000000/0) 64 bit
  .-`` .-```.  ```\/    _.,_ ''-._                                   
 (    '      ,       .-`  | `,    )     Running in stand alone mode
 |`-._`-...-` __...-.``-._|'` _.-'|     Port: 6379
 |    `-._   `._    /     _.-'    |     PID: 6655
  `-._    `-._  `-./  _.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |           http://redis.io        
  `-._    `-._`-.__.-'_.-'    _.-'                                   
 |`-._`-._    `-.__.-'    _.-'_.-'|                                  
 |    `-._`-._        _.-'_.-'    |                                  
  `-._    `-._`-.__.-'_.-'    _.-'                                   
      `-._    `-.__.-'    _.-'                                       
          `-._        _.-'                                           
              `-.__.-'                                               
 
[6655] 27 Aug 12:32:23.522 # Server started, Redis version 2.5.12
[6655] 27 Aug 12:32:23.522 # WARNING overcommit_memory is set to 0! Background save may fail under low memory condition. To fix this issue add 'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[6655] 27 Aug 12:32:23.522 * The server is now ready to accept connections on port 6379

작동하는거야?


$ src/redis-cli
redis> set foo bar
OK
redis> get foo
"bar"

설정

redis.example.conf

간단하게 사용해 보기

유니크 ID 생성


$redis-cli INCR <next_object_id>
(integer) 1

$redis-cli INCR <next_object_id>
(integer) 2

$redis-cli INCR <another_next_object_id>
(integer) 1

$redis-cli GET <next_object_id>
2

$redis-cli GET <another_next_object_id>
1

원자적으로 값을 얻고 지우기


redis> SET TOTO 1
OK
redis> GET TOTO
1
redis> MULTI
OK
redis> GET TOTO
QUEUED
redis> DEL TOTO
QUEUED
redis> EXEC
1. 1
2. (integer) 1
redis> GET TOTO
(nil)

여러개 데이타베이스 사용해보기


redis> select 3
OK

Pipeline


redis> MULTI
OK
redis> LPUSH country_list france 
QUEUED
redis> LPUSH country_list italy
QUEUED
redis> LPUSH country_list germany
QUEUED
redis> INCRBY country_count 3
QUEUED
redis> LRANGE country_list 0 -1
QUEUED
redis> EXEC
1. (integer) 1
2. (integer) 2
3. (integer) 3
4. (integer) 3
5. 
 1. germany
 2. italy
 3. france

FIFO Queue


redis> LPUSH queue1 tom
(integer) 1
redis> LPUSH queue1 dick
(integer) 2
redis> LPUSH queue1 harry
(integer) 3
redis> RPOP queue1
tom
redis> RPOP queue1
dick
redis> RPOP queue1
harry

Simple social Graph


redis> SADD user:1:follows 2
(integer) 1
redis> SADD user:2:followers 1
(integer) 1
redis> SADD user:3:follows 1
(integer) 1
redis> SADD user:1:followers 3
(integer) 1
redis> SADD user:1:follows 3
(integer) 1
redis> SADD user:3:followers 1
(integer) 1
redis> SINTER user:1:follows user:1:followers
1. 3

Tag생성 하고 Tag로 검색하기

태그 생성


SET book:1 {'title' : 'Diving into Python',
'author': 'Mark Pilgrim'}
SET book:2 { 'title' : 'Programing Erlang',
'author': 'Joe Armstrong'}
SET book:3 { 'title' : 'Programing in Haskell',
'author': 'Graham Hutton'}

SADD tag:python 1
SADD tag:erlang 2
SADD tag:haskell 3
SADD tag:programming 1 2 3
SADD tag computing 1 2 3
SADD tag:distributedcomputing 2
SADD tag:FP 2 3

태깅된 아이디 검색


a)  SINTER 'tag:erlang' 'tag:haskell'
    0 results

b)  SINTER 'tag:programming' 'tag:computing'
    3 results: 1, 2, 3

c)  SUNION 'tag:erlang' 'tag:haskell'
    2 results: 2 and 3

d)  SDIFF 'tag:programming' 'tag:haskell'
    2 results: 1 and 2 (haskell is excluded)

Pub/Sub를 사용한 비동기 통신

Connectino A


connectionA> SUBSCRIBE room:chatty
["subscribe", "room:chatty", 1]

connectionA> ...
["message", "room:chatty", "Hello there!"]

connectionA> UNSUBSCRIBE room:chatty
["unsubscribe", "room:chatty", 0]

Connection B


connectionB> PUBLISH room:chatty "Hello there!"
(integer) 1

활용해 보기

Django + Redis + Bootstrap으로 간단한 Top10 보기 예제
^redis-django-score-example.tar.gz

Ubuntu 기준 실행


sudo apt-get install python-virtualenv
virtualenv env --no-site-packages
source env/bin/active
tar xvzf redis-django-score-example.tar.gz
cd example
pip install -r requirements.txt
python ./manage.py runserver 0.0.0.0:8000

참조

  1. http://redis.io
  2. LINE 스토리지, 한달에 수십억 건의 데이터를 Redis와 HBase에 저장하다, http://tech.naver.jp/blog/?p=1420
  3. http://minq.github.com/blog/2012/10/28/redis-config/
  4. http://minq.github.com/blog/2012/10/28/redis-faq/
  5. http://minq.github.com/blog/2012/10/28/redis-commands/
  6. http://rediscookbook.org/