SlideShare uma empresa Scribd logo
1 de 38
Redis 
data design by usecase
목차 
1. 메시지 읽음 처리 
2. 인증 토큰 발행 
3. Redis data 설계 방법 
4. 데이터 설계와 고려 사항
메시지 읽음 처리
이렇게 생긴거요.
읽음 처리 요구 사항 
1. 메시지 창에서 메시지의 읽음 횟수 출력. 
a. 몇 명의 사용자가 메시지를 읽었는지 조회. 
b. 메시지 아이디에 대한 읽음 건수 저장. 
c. 메시지가 삭제되면 메시지 읽음 건수도 삭제.
읽음 건수 데이터 설계(논리) 
1. 사용자 번호, 방 번호로 Hash를 구성. 
2. 메시지 번호를 필드로 하여 건수 저장. 
3. 읽음 건수 조회는 hget 또는 hmget을 사용. 
4. 메세지 삭제 시 읽음 건수 삭제도 같이 이루 
어져야 함.
읽음 건수 데이터 설계(물리) 
Name KeyName Data type 포함정보 
메시지 읽음 rcnt:<user>:<room> hash {message seq, read count}
구현 
1. 메시지 읽음 횟수 저장. 
- hincrby rcnt:<user>:<room> <message Seq> 1 
2. 특정 메시지의 읽음 횟수 조회. 
- hget rcnt:<user>:<room> <message Seq> 
3. 여러 메시지의 읽음 횟수 조회. 
- hmget rcnt:<user>:<room> <message Seq> ... 
4. 특정 방의 메시지 읽음 횟수 조회. 
- hgetall rcnt:<user>:<room>
That’s all???
배포된 바이너리에 버그가 있어서 사 
용자가 창을 열 때마다 API가 호출되 
요!!!! 
헐..
??? !!!
읽음 처리 요구 사항 변경 
1. 메시지 창에서 메시지의 읽음 횟수 출력. 
a. 몇 명의 사용자가 메시지를 읽었는지 조회. 
b. 메시지 아이디에 대한 읽음 건수 저장. 
c. 메시지가 삭제되면 메시지 읽음 건수도 삭제. 
2. 동일한 사용자가 API를 여러 번 호출하더라 
도 읽음 횟수는 단 1회만 증가!
읽음 건수 데이터 설계 v2 (논리) 
1. 방 번호, 메시지 번호로 구성된 키로 Set생성. 
2. Set에 메시지를 읽은 사용자의 사용자 번호 
저장. 
3. 데이터의 조회는 scard 명령을 사용.
읽음 건수 데이터 설계(물리) 
Name KeyName Data type 포함정보 
메시지 읽음 rcnt:<user>:<room>:<message seq> set {read user}
구현 v2(2/2) 
1. 메시지 읽음 횟수 저장 
- sadd rcnt:<user>:<room>:<message seq> <read 
user> 
2. 특정 메시지의 읽음 횟수 조회 
- scard rcnt:<user>:<room>:<message seq> 
3. 여러 메시지의 읽음 횟수 조회 
- scard rcnt:<user>:<room>:<message seq1> 
- scard rcnt:<user>:<room>:<message seq2>
구현 v2(2/2) 
4. 특정 방의 읽음 횟수 조회 
- scard rcnt:<user>:<room>:<message seq1> 
- scard rcnt:<user>:<room>:<message seq2> 
- scard rcnt:<user>:<room>:<message seq3> 
……. ????????????
인증토큰 발행
토큰 발행 요구사항 
1. 만료가 가능한 토큰을 발행한다. 
2. 만료일은 발행 시간으로부터 3일로 지정한다 
3. 새로운 토큰이 발행되면 이전 토큰은 만료 
전까지 사용 가능하다. 
4. 토큰은 부가적인 인증 정보를 가진다. 
(ex. email, nickname, token issue date)
토큰 데이터 설계(논리) 
1. 토큰의 만료는 redis의 expire를 사용. 
2. 인증토큰의 부가 정보는 json 문자열로 저장. 
3. token은 사용자의 id와 발행 시점의 
timestamp를 조합한 문자열에 sha-256 해시를 
수행한 값을 사용. 
4. 문자열에 token을 키로 하여 인증 정보를 저 
장
토큰 데이터 설계(물리) 
Name KeyName Data type 포함정보 
인증토큰 token:<token string> String {email, userno, nick}
구현 
1. Token 발행 
- String token = sha256(id + timestamp) 
- setex token:<token> 
{'mail':'aaa@naver.com','nick':'test','userNo':'10 
46'} 259200 
2. token 검증 
- get token:<token>
어때요? 참 쉽죠?
BUT!!! 그러나!!!
토큰발행 변경 요구사항 
id별 활성 token을 조회할 수 있게 해주세요
토큰 데이터 설계 v2 (논리) 
1. 만료기능은 redis의 expire를 사용 
2. 인증과 관련된 추가 정보는 json 문자열로 저장. 
3. token은 사용자의 id와 발행 시점의 timestamp를 조합 
한 문자열에 sha-256 해시를 수행한 값을 사용. 
4. 문자열에 token을 키로 하여 인증 정보를 저장. 
5. 사용자 번호로 hash를 생성. 
6. hash에 사용자 token과 timestamp를 저장.
토큰 데이터 설계 v2 (물리) 
Name KeyName Data type 포함정보 
인증토큰 token:<token 
string> 
String {email, userno, nick} 
토큰목록 tokenlist:<userNo> hash {token, expire date}
구현 v2(1/2) 
1. Token 발행(use multi command) 
- String token = sha256(id + timestamp) 
- setex expire <token> 
{"email":"aaa@naver.com","nickName":"test","userNo":"10 
46"} 259200 
- hset <userid>, <token>, timestamp
구현 v2(2/2) 
2. token 검증 
- get token:<token> 
3. 활성 token 조회 
- hgetall <userid> 
- timestamp를 기준으로 출력 여부 결정.
수정이 완료 되었군요. 
운영서버로 ㄱㄱ
BUT!!! 또 그러나!!!
HASH 내부에 만료된 token은 언제 삭 
제하지?
redis 2.8의 새 기능 Keyspace events
Redis Keyspace Notifications 
1. 키의 변경이 발생하면 PUB/SUB을 통해서 확인가능. 
- 즉, expire된 키의 이름을 알 수 있음. 
- config set notify-keyspace-events Ex 
- psubscribe "__keyevent@*" 
※ SUB을 받아서 처리하는 별도의 프로그램 작성 필요. 
※ 더 많은 내용 http://redis.io/topics/notifications 참조 
K Keyspace events, published with __keyspace@<db>__ prefix. 
E Keyevent events, published with __keyevent@<db>__ prefix. 
g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... 
...
이렇게 하여 인증 토큰을 
자알 구현했습니다. 
끄읕~~
Redis data 설계 주안점 (1/2) 
1. 모든 데이터를 키에 저장할 수 있는가? 
- 키 만 조회 하여 업무를 처리할 수 있도록 구성. 
2. 자료구조 Set, Hash, List등으로 구현이 가능한가? 
- 여러개의 명령을 사용하더라도 실행시간이 O(1)인지. 
- 우리에겐 Lua가 있다. 
4. 데이터 사용 성향에 따라 다른 데이터 구조 선택 필요. 
- 빠른 쓰기가 필요한지 빠른 읽기가 필요한지 
- Hash와 Sorted set에 대한 trade 가능하면 Hash로.
Redis data 설계 주안점 (2/2) 
5. 단순한 데이터 조회 패턴을 가지는가? 
- RDB의 where 필터링은 불가!!! 
6. 숫자 데이터가 많은가? 
- 카운터와 같은 숫자 데이터 저장에 강함. 
3. Lua 사용시 전체 시간복잡도는 O(log n)을 초과 하지 않 
도록 하라.
Lua 사용 주의사항 
1. 예측 불가능한 Loop문을 사용하지 말것. 
- ex) while(true) 
※ Lua 스크립트의 실행은 원자성을 가짐. 
2. 에러 처리에 신경쓸것. 
- ex) 조회한 데이터가 존재하는지 확인.
Redis data design by usecase

Mais conteúdo relacionado

Mais procurados

WSO2 Identity Server - Product Overview
WSO2 Identity Server - Product OverviewWSO2 Identity Server - Product Overview
WSO2 Identity Server - Product OverviewWSO2
 
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018Amazon Web Services Korea
 
[OSSParis 2015] The OpenID Connect Protocol
[OSSParis 2015] The OpenID Connect Protocol[OSSParis 2015] The OpenID Connect Protocol
[OSSParis 2015] The OpenID Connect ProtocolClément OUDOT
 
Cloud computing and OpenStack
Cloud computing and OpenStackCloud computing and OpenStack
Cloud computing and OpenStackMinh Le
 
Event Driven-Architecture from a Scalability perspective
Event Driven-Architecture from a Scalability perspectiveEvent Driven-Architecture from a Scalability perspective
Event Driven-Architecture from a Scalability perspectiveJonas Bonér
 
Loosely or lousily coupled - Understanding communication patterns in microser...
Loosely or lousily coupled - Understanding communication patterns in microser...Loosely or lousily coupled - Understanding communication patterns in microser...
Loosely or lousily coupled - Understanding communication patterns in microser...Bernd Ruecker
 
Token, token... From SAML to OIDC
Token, token... From SAML to OIDCToken, token... From SAML to OIDC
Token, token... From SAML to OIDCShiu-Fun Poon
 
Deep Dive into Durable Functions
Deep Dive into Durable FunctionsDeep Dive into Durable Functions
Deep Dive into Durable FunctionsJoonas Westlin
 
디지털 해적들로부터 영상 콘텐츠 보호하기 – 황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...
디지털 해적들로부터 영상 콘텐츠 보호하기 –  황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...디지털 해적들로부터 영상 콘텐츠 보호하기 –  황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...
디지털 해적들로부터 영상 콘텐츠 보호하기 – 황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...Amazon Web Services Korea
 
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020AWSKRUG - AWS한국사용자모임
 
Kafka as an event store - is it good enough?
Kafka as an event store - is it good enough?Kafka as an event store - is it good enough?
Kafka as an event store - is it good enough?Guido Schmutz
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20Amazon Web Services Korea
 
Mit 2014 introduction to open id connect and o-auth 2
Mit 2014   introduction to open id connect and o-auth 2Mit 2014   introduction to open id connect and o-auth 2
Mit 2014 introduction to open id connect and o-auth 2Justin Richer
 
LASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. OauthLASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. OauthMike Schwartz
 
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel Aviv
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel AvivElastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel Aviv
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel AvivAmazon Web Services
 
Domain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and MicroservicesDomain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and MicroservicesRadosław Maziarka
 
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013Amazon Web Services
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinJava User Group Latvia
 

Mais procurados (20)

WSO2 Identity Server - Product Overview
WSO2 Identity Server - Product OverviewWSO2 Identity Server - Product Overview
WSO2 Identity Server - Product Overview
 
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018
AWS KMS를 활용하여 안전한 AWS 환경을 구축하기 위한 전략::임기성::AWS Summit Seoul 2018
 
Amazon EC2:Masterclass
Amazon EC2:MasterclassAmazon EC2:Masterclass
Amazon EC2:Masterclass
 
OAuth2 + API Security
OAuth2 + API SecurityOAuth2 + API Security
OAuth2 + API Security
 
[OSSParis 2015] The OpenID Connect Protocol
[OSSParis 2015] The OpenID Connect Protocol[OSSParis 2015] The OpenID Connect Protocol
[OSSParis 2015] The OpenID Connect Protocol
 
Cloud computing and OpenStack
Cloud computing and OpenStackCloud computing and OpenStack
Cloud computing and OpenStack
 
Event Driven-Architecture from a Scalability perspective
Event Driven-Architecture from a Scalability perspectiveEvent Driven-Architecture from a Scalability perspective
Event Driven-Architecture from a Scalability perspective
 
Loosely or lousily coupled - Understanding communication patterns in microser...
Loosely or lousily coupled - Understanding communication patterns in microser...Loosely or lousily coupled - Understanding communication patterns in microser...
Loosely or lousily coupled - Understanding communication patterns in microser...
 
Token, token... From SAML to OIDC
Token, token... From SAML to OIDCToken, token... From SAML to OIDC
Token, token... From SAML to OIDC
 
Deep Dive into Durable Functions
Deep Dive into Durable FunctionsDeep Dive into Durable Functions
Deep Dive into Durable Functions
 
디지털 해적들로부터 영상 콘텐츠 보호하기 – 황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...
디지털 해적들로부터 영상 콘텐츠 보호하기 –  황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...디지털 해적들로부터 영상 콘텐츠 보호하기 –  황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...
디지털 해적들로부터 영상 콘텐츠 보호하기 – 황윤상 AWS 솔루션즈 아키텍트, 김준호 잉카엔트웍스 매니저:: AWS Cloud Week ...
 
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
온라인 주문 서비스를 서버리스 아키텍쳐로 구축하기 - 김태우(Classmethod) :: AWS Community Day Online 2020
 
Kafka as an event store - is it good enough?
Kafka as an event store - is it good enough?Kafka as an event store - is it good enough?
Kafka as an event store - is it good enough?
 
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
AWS 기반의 마이크로 서비스 아키텍쳐 구현 방안 :: 김필중 :: AWS Summit Seoul 20
 
Mit 2014 introduction to open id connect and o-auth 2
Mit 2014   introduction to open id connect and o-auth 2Mit 2014   introduction to open id connect and o-auth 2
Mit 2014 introduction to open id connect and o-auth 2
 
LASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. OauthLASCON 2017: SAML v. OpenID v. Oauth
LASCON 2017: SAML v. OpenID v. Oauth
 
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel Aviv
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel AvivElastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel Aviv
Elastic Load Balancing Deep Dive and Best Practices - Pop-up Loft Tel Aviv
 
Domain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and MicroservicesDomain Driven Design - Strategic Patterns and Microservices
Domain Driven Design - Strategic Patterns and Microservices
 
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013
Delegating Access to your AWS Environment (SEC303) | AWS re:Invent 2013
 
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry BuzdinModern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
Modern Security with OAuth 2.0 and JWT and Spring by Dmitry Buzdin
 

Destaque

Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examplesTerry Cho
 
Scaling Crashlytics: Building Analytics on Redis 2.6
Scaling Crashlytics: Building Analytics on Redis 2.6Scaling Crashlytics: Building Analytics on Redis 2.6
Scaling Crashlytics: Building Analytics on Redis 2.6Crashlytics
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Rediscacois
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Itamar Haber
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in PracticeNoah Davis
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redisDvir Volk
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askCarlos Abalde
 

Destaque (7)

Redis data modeling examples
Redis data modeling examplesRedis data modeling examples
Redis data modeling examples
 
Scaling Crashlytics: Building Analytics on Redis 2.6
Scaling Crashlytics: Building Analytics on Redis 2.6Scaling Crashlytics: Building Analytics on Redis 2.6
Scaling Crashlytics: Building Analytics on Redis 2.6
 
High-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using RedisHigh-Volume Data Collection and Real Time Analytics Using Redis
High-Volume Data Collection and Real Time Analytics Using Redis
 
Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)Redis Use Patterns (DevconTLV June 2014)
Redis Use Patterns (DevconTLV June 2014)
 
Redis in Practice
Redis in PracticeRedis in Practice
Redis in Practice
 
Kicking ass with redis
Kicking ass with redisKicking ass with redis
Kicking ass with redis
 
Everything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to askEverything you always wanted to know about Redis but were afraid to ask
Everything you always wanted to know about Redis but were afraid to ask
 

Semelhante a Redis data design by usecase

Node-express 채팅 서버 개발기
Node-express 채팅 서버 개발기Node-express 채팅 서버 개발기
Node-express 채팅 서버 개발기정웅 박
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platformJay JH Park
 
Hadoop security DeView 2014
Hadoop security DeView 2014Hadoop security DeView 2014
Hadoop security DeView 2014Gruter
 
Mongo db 시작하기
Mongo db 시작하기Mongo db 시작하기
Mongo db 시작하기OnGameServer
 
Blockchain 2nd ethereum_core
Blockchain 2nd ethereum_coreBlockchain 2nd ethereum_core
Blockchain 2nd ethereum_coreihpark92
 
(131102) #fitalk get windows logon password in memory dump
(131102) #fitalk   get windows logon password in memory dump(131102) #fitalk   get windows logon password in memory dump
(131102) #fitalk get windows logon password in memory dumpINSIGHT FORENSIC
 
[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)NAVER D2
 
HTTP 완벽가이드- 19장 배포시스템
HTTP 완벽가이드- 19장 배포시스템HTTP 완벽가이드- 19장 배포시스템
HTTP 완벽가이드- 19장 배포시스템박 민규
 
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기리스펙토링 세미나 - 나만의 카카오 챗봇 만들기
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기Wooyoung Ko
 
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 APINAVER Engineering
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발흥배 최
 
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdf
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdfOS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdf
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdfHo Jeong Im
 
[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석ethconkr
 
IT 일반기술 강의자료_ed10
IT 일반기술 강의자료_ed10IT 일반기술 강의자료_ed10
IT 일반기술 강의자료_ed10hungrok
 
Ch1 일래스틱서치 클러스터 시작
Ch1 일래스틱서치 클러스터 시작Ch1 일래스틱서치 클러스터 시작
Ch1 일래스틱서치 클러스터 시작Minchul Jung
 
막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js연웅 조
 

Semelhante a Redis data design by usecase (20)

Node-express 채팅 서버 개발기
Node-express 채팅 서버 개발기Node-express 채팅 서버 개발기
Node-express 채팅 서버 개발기
 
Portfolio
PortfolioPortfolio
Portfolio
 
세션1. block chain as a platform
세션1. block chain as a platform세션1. block chain as a platform
세션1. block chain as a platform
 
Hadoop security DeView 2014
Hadoop security DeView 2014Hadoop security DeView 2014
Hadoop security DeView 2014
 
Mongo db 시작하기
Mongo db 시작하기Mongo db 시작하기
Mongo db 시작하기
 
Blockchain 2nd ethereum_core
Blockchain 2nd ethereum_coreBlockchain 2nd ethereum_core
Blockchain 2nd ethereum_core
 
(131102) #fitalk get windows logon password in memory dump
(131102) #fitalk   get windows logon password in memory dump(131102) #fitalk   get windows logon password in memory dump
(131102) #fitalk get windows logon password in memory dump
 
[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)[211] HBase 기반 검색 데이터 저장소 (공개용)
[211] HBase 기반 검색 데이터 저장소 (공개용)
 
HTTP 완벽가이드- 19장 배포시스템
HTTP 완벽가이드- 19장 배포시스템HTTP 완벽가이드- 19장 배포시스템
HTTP 완벽가이드- 19장 배포시스템
 
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기리스펙토링 세미나 - 나만의 카카오 챗봇 만들기
리스펙토링 세미나 - 나만의 카카오 챗봇 만들기
 
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API
[16]Obfuscation 101 : 난독화, 프로가드, R8, 트랜스포머 API
 
C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발C#을 사용한 빠른 툴 개발
C#을 사용한 빠른 툴 개발
 
Html5
Html5 Html5
Html5
 
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdf
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdfOS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdf
OS Process, Thread, CPU Scheduling에 대해 알아봅시다.pdf
 
[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석[ETHCon Korea 2019] Kang Hyungseok 강형석
[ETHCon Korea 2019] Kang Hyungseok 강형석
 
IT 일반기술 강의자료_ed10
IT 일반기술 강의자료_ed10IT 일반기술 강의자료_ed10
IT 일반기술 강의자료_ed10
 
Ch1 일래스틱서치 클러스터 시작
Ch1 일래스틱서치 클러스터 시작Ch1 일래스틱서치 클러스터 시작
Ch1 일래스틱서치 클러스터 시작
 
3장
3장3장
3장
 
리로그인 Relogin: 코드스테이츠 데모데이
리로그인 Relogin: 코드스테이츠 데모데이리로그인 Relogin: 코드스테이츠 데모데이
리로그인 Relogin: 코드스테이츠 데모데이
 
막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js막하는 스터디 첫 번째 만남 Node.js
막하는 스터디 첫 번째 만남 Node.js
 

Mais de Kris Jeong

Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략
Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략
Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략Kris Jeong
 
Going asynchronous with netty - SOSCON 2015
Going asynchronous with netty - SOSCON 2015Going asynchronous with netty - SOSCON 2015
Going asynchronous with netty - SOSCON 2015Kris Jeong
 
This is redis - feature and usecase
This is redis - feature and usecaseThis is redis - feature and usecase
This is redis - feature and usecaseKris Jeong
 
이것이 레디스다.
이것이 레디스다.이것이 레디스다.
이것이 레디스다.Kris Jeong
 
REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redisKris Jeong
 

Mais de Kris Jeong (6)

Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략
Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략
Soscon2017 오픈소스를 활용한 마이크로 서비스의 캐시 전략
 
Going asynchronous with netty - SOSCON 2015
Going asynchronous with netty - SOSCON 2015Going asynchronous with netty - SOSCON 2015
Going asynchronous with netty - SOSCON 2015
 
This is redis - feature and usecase
This is redis - feature and usecaseThis is redis - feature and usecase
This is redis - feature and usecase
 
이것이 레디스다.
이것이 레디스다.이것이 레디스다.
이것이 레디스다.
 
Active MQ
Active MQActive MQ
Active MQ
 
REDIS intro and how to use redis
REDIS intro and how to use redisREDIS intro and how to use redis
REDIS intro and how to use redis
 

Redis data design by usecase

  • 1. Redis data design by usecase
  • 2. 목차 1. 메시지 읽음 처리 2. 인증 토큰 발행 3. Redis data 설계 방법 4. 데이터 설계와 고려 사항
  • 5. 읽음 처리 요구 사항 1. 메시지 창에서 메시지의 읽음 횟수 출력. a. 몇 명의 사용자가 메시지를 읽었는지 조회. b. 메시지 아이디에 대한 읽음 건수 저장. c. 메시지가 삭제되면 메시지 읽음 건수도 삭제.
  • 6. 읽음 건수 데이터 설계(논리) 1. 사용자 번호, 방 번호로 Hash를 구성. 2. 메시지 번호를 필드로 하여 건수 저장. 3. 읽음 건수 조회는 hget 또는 hmget을 사용. 4. 메세지 삭제 시 읽음 건수 삭제도 같이 이루 어져야 함.
  • 7. 읽음 건수 데이터 설계(물리) Name KeyName Data type 포함정보 메시지 읽음 rcnt:<user>:<room> hash {message seq, read count}
  • 8. 구현 1. 메시지 읽음 횟수 저장. - hincrby rcnt:<user>:<room> <message Seq> 1 2. 특정 메시지의 읽음 횟수 조회. - hget rcnt:<user>:<room> <message Seq> 3. 여러 메시지의 읽음 횟수 조회. - hmget rcnt:<user>:<room> <message Seq> ... 4. 특정 방의 메시지 읽음 횟수 조회. - hgetall rcnt:<user>:<room>
  • 10. 배포된 바이너리에 버그가 있어서 사 용자가 창을 열 때마다 API가 호출되 요!!!! 헐..
  • 12. 읽음 처리 요구 사항 변경 1. 메시지 창에서 메시지의 읽음 횟수 출력. a. 몇 명의 사용자가 메시지를 읽었는지 조회. b. 메시지 아이디에 대한 읽음 건수 저장. c. 메시지가 삭제되면 메시지 읽음 건수도 삭제. 2. 동일한 사용자가 API를 여러 번 호출하더라 도 읽음 횟수는 단 1회만 증가!
  • 13. 읽음 건수 데이터 설계 v2 (논리) 1. 방 번호, 메시지 번호로 구성된 키로 Set생성. 2. Set에 메시지를 읽은 사용자의 사용자 번호 저장. 3. 데이터의 조회는 scard 명령을 사용.
  • 14. 읽음 건수 데이터 설계(물리) Name KeyName Data type 포함정보 메시지 읽음 rcnt:<user>:<room>:<message seq> set {read user}
  • 15. 구현 v2(2/2) 1. 메시지 읽음 횟수 저장 - sadd rcnt:<user>:<room>:<message seq> <read user> 2. 특정 메시지의 읽음 횟수 조회 - scard rcnt:<user>:<room>:<message seq> 3. 여러 메시지의 읽음 횟수 조회 - scard rcnt:<user>:<room>:<message seq1> - scard rcnt:<user>:<room>:<message seq2>
  • 16. 구현 v2(2/2) 4. 특정 방의 읽음 횟수 조회 - scard rcnt:<user>:<room>:<message seq1> - scard rcnt:<user>:<room>:<message seq2> - scard rcnt:<user>:<room>:<message seq3> ……. ????????????
  • 18. 토큰 발행 요구사항 1. 만료가 가능한 토큰을 발행한다. 2. 만료일은 발행 시간으로부터 3일로 지정한다 3. 새로운 토큰이 발행되면 이전 토큰은 만료 전까지 사용 가능하다. 4. 토큰은 부가적인 인증 정보를 가진다. (ex. email, nickname, token issue date)
  • 19. 토큰 데이터 설계(논리) 1. 토큰의 만료는 redis의 expire를 사용. 2. 인증토큰의 부가 정보는 json 문자열로 저장. 3. token은 사용자의 id와 발행 시점의 timestamp를 조합한 문자열에 sha-256 해시를 수행한 값을 사용. 4. 문자열에 token을 키로 하여 인증 정보를 저 장
  • 20. 토큰 데이터 설계(물리) Name KeyName Data type 포함정보 인증토큰 token:<token string> String {email, userno, nick}
  • 21. 구현 1. Token 발행 - String token = sha256(id + timestamp) - setex token:<token> {'mail':'aaa@naver.com','nick':'test','userNo':'10 46'} 259200 2. token 검증 - get token:<token>
  • 24. 토큰발행 변경 요구사항 id별 활성 token을 조회할 수 있게 해주세요
  • 25. 토큰 데이터 설계 v2 (논리) 1. 만료기능은 redis의 expire를 사용 2. 인증과 관련된 추가 정보는 json 문자열로 저장. 3. token은 사용자의 id와 발행 시점의 timestamp를 조합 한 문자열에 sha-256 해시를 수행한 값을 사용. 4. 문자열에 token을 키로 하여 인증 정보를 저장. 5. 사용자 번호로 hash를 생성. 6. hash에 사용자 token과 timestamp를 저장.
  • 26. 토큰 데이터 설계 v2 (물리) Name KeyName Data type 포함정보 인증토큰 token:<token string> String {email, userno, nick} 토큰목록 tokenlist:<userNo> hash {token, expire date}
  • 27. 구현 v2(1/2) 1. Token 발행(use multi command) - String token = sha256(id + timestamp) - setex expire <token> {"email":"aaa@naver.com","nickName":"test","userNo":"10 46"} 259200 - hset <userid>, <token>, timestamp
  • 28. 구현 v2(2/2) 2. token 검증 - get token:<token> 3. 활성 token 조회 - hgetall <userid> - timestamp를 기준으로 출력 여부 결정.
  • 29. 수정이 완료 되었군요. 운영서버로 ㄱㄱ
  • 31. HASH 내부에 만료된 token은 언제 삭 제하지?
  • 32. redis 2.8의 새 기능 Keyspace events
  • 33. Redis Keyspace Notifications 1. 키의 변경이 발생하면 PUB/SUB을 통해서 확인가능. - 즉, expire된 키의 이름을 알 수 있음. - config set notify-keyspace-events Ex - psubscribe "__keyevent@*" ※ SUB을 받아서 처리하는 별도의 프로그램 작성 필요. ※ 더 많은 내용 http://redis.io/topics/notifications 참조 K Keyspace events, published with __keyspace@<db>__ prefix. E Keyevent events, published with __keyevent@<db>__ prefix. g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... ...
  • 34. 이렇게 하여 인증 토큰을 자알 구현했습니다. 끄읕~~
  • 35. Redis data 설계 주안점 (1/2) 1. 모든 데이터를 키에 저장할 수 있는가? - 키 만 조회 하여 업무를 처리할 수 있도록 구성. 2. 자료구조 Set, Hash, List등으로 구현이 가능한가? - 여러개의 명령을 사용하더라도 실행시간이 O(1)인지. - 우리에겐 Lua가 있다. 4. 데이터 사용 성향에 따라 다른 데이터 구조 선택 필요. - 빠른 쓰기가 필요한지 빠른 읽기가 필요한지 - Hash와 Sorted set에 대한 trade 가능하면 Hash로.
  • 36. Redis data 설계 주안점 (2/2) 5. 단순한 데이터 조회 패턴을 가지는가? - RDB의 where 필터링은 불가!!! 6. 숫자 데이터가 많은가? - 카운터와 같은 숫자 데이터 저장에 강함. 3. Lua 사용시 전체 시간복잡도는 O(log n)을 초과 하지 않 도록 하라.
  • 37. Lua 사용 주의사항 1. 예측 불가능한 Loop문을 사용하지 말것. - ex) while(true) ※ Lua 스크립트의 실행은 원자성을 가짐. 2. 에러 처리에 신경쓸것. - ex) 조회한 데이터가 존재하는지 확인.

Notas do Editor

  1. 몇 가지 예제를 통해서 데이터 구조를 설계하는 방법을 알아봄.
  2. 예제는 읽음 카운트 저장, 인증 토큰 발행, 그리고 시간이 허락한다면 검색어 자동완성
  3. 이걸 RDB로 구현 하자면 살짝 머리 아파 집니다.
  4. 먼저 구체적으로 요구 사항을 정리해보죠. 레디스의 어떤 데이터형으로 이것을 처리 할 수 있을지 먼저 생각하는것이 중요. RDB의 테이블에서 인덱스를 구성하고 인덱스 만으로 조회할 수 있도록 데이터를 구성.
  5. 이 논리 설계에는 아래의 전재가 깔림 1. 메시지는 영구 저장되지 않음. 2. “한 명의 사용자가 하나의 방에서 수만 건의 메세지를 전송하지 않을 것이다”
  6. hincrby rcnt:6333:8259 12345 1
  7. 사용자 번호 6333 방번호 8259 메세지 일련번호 12345 ex) 6333사용자가 8259 방에서 120번 사용자의 메시지인 “hi”를 읽었는데, 해당 메시지 번호는 12345 hincrby rcnt:120:34984 26554 1
  8. 여기서 끝나면 너무 싱겁죠.
  9. 어떻게 구현해야 할까? 동일한 요청인지 어떻게 구분하지? 플래그 처리? 플래그는 bitset으로 처리 가능 레디스에서 지원하는 데이터 구조 중에 Set데이터를 사용하여 처리 하도록 결정. 실제로 여기서는 이 방법이 가장 무난함.
  10. redis benchmark 몇 가지 선택 사항이 존재. 특정 방의 읽음 횟수 조회 API를 제거하는 방법. 읽음 횟수를 100건씩 잘라서 가져오는 API를 만드는 방법.
  11. 예제 보기
  12. 기본적으로 Lua 스크립트는 레디스 Command와 동일한 레벨의 실행 수준임. 즉, 스크립트는 완전 독립적으로 실행되며 Lua가 실행되는 동안 다른 명령의 수행이 이루어지지 않음.