노력과 삽질 퇴적물

Memcached&Redis(레디스) 본문

프로그래밍note/서버 및 통신

Memcached&Redis(레디스)

MTG 2018. 4. 27. 16:00






1. 특징 및 차이점


Memcached

Redis(레디스)

 데이터를 메모리에만 저장.

 멀티스레드

 수평적 확장이 쉬움

 문자열 기반 저장

 데이터를 디스크에 저장.

 싱글스레드

 수평적 확장이 어려움(3.0이전 기준)

 다양한 자료구조 저장 지원.






2. Memcached


1) 데이터 처리

해쉬 테이블 데이터구조는 bucket배열로 배열의 크기는 항상 2의 거듭제곱.



2) 샘플코드

* 맴캐쉬 클라이언트 초기화는 생략.

①저장

1
2
3
4
5
6
7
8
9
10
11
MemcachedClient client = new MemcachedClient(...);
String memcacheKey = "StoreKey";
int expireTime = 1000;// max expire time: 60*60*24*30 s(= 30days)
String json = "... ... ...";
 
try {
    ... ...
    client.getClient().set( memCacheKey, expireTime, json );
catch (Throwable exception) {
    ... ... ...
}
cs


②읽기

1
2
3
4
5
6
7
8
9
10
MemcachedClient client = new MemcachedClient(...);
String memcacheKey = "StoreKey";
String memcacheValue = null;
 
try {
    ... ...
    memcacheValue = (String)client.getClient().get( memcacheKey );
catch (Throwable exception) {
    ... ... ...
}
cs


③삭제

1
2
3
4
5
6
7
8
9
10
MemcachedClient client = new MemcachedClient(...);
String memcacheKey = "StoreKey";
boolean result = false;
 
try {
    result = client.delete(memCacheKey).get();
    ... ... ...
catch (Throwable exception) {
    ... ... ...
}
cs






3. Redis


1) 데이터 처리

① 데이타 저장방식

 snapshotting
 (RDB방식)

 메모리 내용을 디스크 전체에 복사.
 메모리를 스냅샷찍는데 소모되는 시간값이 크고, 서버가 죽을경우 스냅샷이후의 데이터는 보장못한다.

 AOF
 (Append on file)

 레디스의 모든 write/update 연산자체를 log파일로 생성.
 연산에 대한 모든 로그를 생성하기때문에 서버 재시작시 데이터를 안정적으로 보장하지만, 처리되는 로그파일의 용량이 크고 재시작시 속도가 느리다.


② 자료구조

> Bucket-Chained Linked List 구조 사용

> value에서 지원되는 자료형

: String, Set, Sorted Set, Hashes, List

> 단일 노드와 최대 15개의 샤드 클러스터가 지원(메모리 데이터를 3.55TiB까지 확장가능)

: 저장된 데이타에 대한 연산이나 추가 작업 가능. (합집합,교집합)


③ 생명주기

> 자동삭제 정책

 Active

 클라이언트가 데이터에 접근시에만 만료여부를 체크

 Passive

 주기적으로 key들을 100개씩 스캔해서 삭제(무작위 선출)



2) 주요명령

> Command reference – Redis

Redis ordered set - w3big.com

> scan은 기본적으로 테이블에 있는 블럭을 가져와서 처리하는 방식.

 

 반환타입

 SCAN

 키값 목록 배열
 SSCAN Set
 HSCAN Hash

 ZSCAN

 정렬된 Set 멤버



3) 장점&단점

① 장점

> 캐싱이 쉽다

> 쉬운 설치와 저렵한 서버이용

> 다양한 데이터 타입 지원.


② 단점

> Chained Linked List구조상, Bucket의 데이터가 많으면 탐색속도 저하.

> joins/query 부재

> 경우에 따라서 lua스크립트 필요



4) Master&Slave

> 트래픽을 분산시키는 replication에 필요.

 master R/W가능
 slave

 (기본값)R가능.

 부모-자식 프로세스와 달리, 마스터가 죽는다고 해서 slave까지 죽진 않음.

 단, 2.6버전부터는 슬레이브는 read only[각주:1]






4. 실무Jedis[#]


1) Jesdis

> #링크



2) 실시간 랭킹보드

> 처리할 데이터양이 많은거라, sorted sets(zset)+Uniqueness+Ordering 조합으로 구현가능.

How to Implement a Simple Redis Leaderboard - 1&1



3) 샘플코드

* JAVA & Jesdis기반

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*
    https://redis.io/commands/zrevrank
    ZREVRANK key member    
    member with the highest score has rank 0
*/
JedisPool pool = new JedisPool(... ... ...); 
Jedis jedis = pool.getResource();
 
Long result = 0L;
Jedis jedis = RedisManager.getClient();
    
try{
    result = jedis.zrevrank(key, memberNo);
    if(result == null)
    {
        //do-somthing.
    }
    else
    {
        result = result+1;//member with the highest score has rank 0
    }
    }catch(JedisException exception){
        //do-somthing.
    }finally{
        jedis.close();
    }
    
    return result;
}
cs






기타. 참조자료


AWS | Amazon ElastiCache – 인 메모리 데이터 스토어 및 캐시


게임서비스를 위한 ElastiCache 활용 전략 :: 구승모 솔루션즈 아키텍트 :: Gaming on AWS 2016

Bitnami Redis for AWS Cloud

Redis의 SCAN은 어떻게 동작하는가?

조대협의 블로그 :: In memory dictionary Redis 소개


카카오 "레디스, 잘못쓰면 망한다" - 지디넷코리아


The advantages ans disadvantages of Redis...1 answer - Quora






기타. 변경이력


일자

변경이력

2018-04-27

 초안

  1. https://github.com/xetorthio/jedis/wiki/Getting-started Note: since Redis 2.6 slaves are read only by default, so write requests to them will result in an error. [본문으로]