redis 문법

2019. 4. 23. 10:5999. 정리전 - IT/11. Java

츄르처 : https://bstar36.tistory.com/347

 

[Redis] 데이터 타입

1. 데이터 처리 명령어 1.1 문자열 데이터 처리 저장 가능한 문자열의 크기는 최대 512MB 이다. set, get 하나의 문자열을 저장하고 조회 한다. mset, mget 여러 개의 문자열을 저장하고 조회 한다. (Multi를 뜻하..

bstar36.tistory.com

1. 데이터 처리 명령어

   1.1 문자열 데이터 처리

        1) set, get 하나의 문자열을 저장하고 조회 한다. (~512M)
        2) 
mset, mget 여러 개의 문자열을 저장하고 조회 한다. (m = multi), (z = set , h = hash)
        3)
없는 데이터 조회 시에는 nil 리턴
        4) 
기존에 있는 key값을 입력하면 기존 값이 업데이트 된다.
           
만약 기존에 key값이 없으면 값을 세팅하고,
           key
값이 세팅 되어 있으면 새로운 값을 넣지 않는 로직을 구현하고자 한다면,
           
먼저 get으로 데이터를 조회 후에 set으로 데이터를 넣는 방법 밖에 .

set key value [EX seconds] [PX milliseconds] [NX|XX]

mset key value [key value ...]

get key

mget key [key ...]

127.0.0.1:6379> set test1 hi
OK

127.0.0.1:6379> set test2 Nice
OK

127.0.0.1:6379> set test3 to
OK

127.0.0.1:6379> set test4 meet
OK

127.0.0.1:6379> set test5 you
OK

127.0.0.1:6379> get test1
"hi"

127.0.0.1:6379> get test2
"Nice"

127.0.0.1:6379> get test3
"to"

127.0.0.1:6379> get test4
"meet"

127.0.0.1:6379> get test5
"you"

127.0.0.1:6379> get test6  <-- 없는 데이터 조회
(nil)

127.0.0.1:6379> set test1 youngjoon
OK

127.0.0.1:6379> get test1
"youngjoon"

127.0.0.1:6379> mset t1 hi t2 Nice t3 to t4 meet t5 you
OK

127.0.0.1:6379> mget t1 t2 t3 t4 t5
1) "hi"
2) "Nice"
3) "to"
4) "meet"
5) "you"

127.0.0.1:6379> mget t6   <-- 없는 데이터 조회
(nil)

 

 

 

 

 

 

 

 

 

 

 

 

        5) 여러 개의 데이터를 mget mset 하는 경우는 setnx / msetnx 명령(실패  경우 전체가 실패)를 이용
            key
값이 없어서 정상적으로 세팅이 되면 1, 실패 하면 0

127.0.0.1:6379> mset t1:v1 hi t1:v2 nice t1:v3 to t1:v4 meet t1:v5 you
OK

127.0.0.1:6379> mget t1:v1 t1:v2 t1:v3 t1:v4 t1:v5
1) "hi"
2) "nice"
3) "to"
4) "meet"
5) "you"

127.0.0.1:6379> mset t1:v5 youngjoon   <-- key 값이 업데이트 
OK

127.0.0.1:6379> mget  t1:v1 t1:v2 t1:v3 t1:v4 t1:v5
1) "hi"
2) "nice"
3) "to"
4) "meet"
5) "youngjoon"

127.0.0.1:6379> setnx t1:v5 sujin  <-- sujin로 key값을 설정 하려고 하는데 기존 키 값이 있어서
(integer) 0                             <-- 실패 (리턴값 = 0)

127.0.0.1:6379> mget  t1:v1 t1:v2 t1:v3 t1:v4 t1:v5
1) "hi"
2) "nice"
3) "to"
4) "meet"
5) "youngjoon"

127.0.0.1:6379> msetnx t1:v6 ! t1:v5 sujin  <-- t1:v6 key는 없지만 t1:v5 key값이 있으므로 실패
(integer) 0

127.0.0.1:6379> mget  t1:v1 t1:v2 t1:v3 t1:v4 t1:v5 t1:v6
1) "hi"
2) "nice"
3) "to"
4) "meet"
5) "youngjoon"
6) (nil)        <-- t1:v6 값이 없어서 nil 리턴

127.0.0.1:6379> msetnx t1:v6 !
(integer) 1    <- 성공하면 1 리턴

127.0.0.1:6379> mget  t1:v1 t1:v2 t1:v3 t1:v4 t1:v5 t1:v6
1) "hi"
2) "nice"
3) "to"
4) "meet"
5) "youngjoon"
6) "!"

        6) 기존에 key 있을 경우 업데이트를   이전 값을 리턴  주는 getset 명령어

127.0.0.1:6379> getset t1:v5 sujin
"youngjoon"

127.0.0.1:6379> get t1:v5
"sujin"

127.0.0.1:6379> getset t1:v7 Bye      <-- 이전 key 값이 존재 하지 않았으면 nil 값을 리턴
(nil)

        7) 문자열의 길이는 strlen 명령어를 이용한다.

127.0.0.1:6379> strlen t1:v5
(integer) 4

 

   1.2 숫자형 데이터 처리

        1) 숫자형 데이터에 대하여 값을 증가 시키거나 감소 시키는 incr, decr 명령어를 사용 (기본단위 1)
        2) 
명령어 뒤에 by 추가 하면 지정한 값으로  값을 증가시킴 ( incrby, decrby )

127.0.0.1:6379> mset t2:v1 1 t2:v2 0 t2:v3 -5
OK

127.0.0.1:6379> incr t2:v1
(integer) 2

127.0.0.1:6379> decr t2:v2
(integer) -1

127.0.0.1:6379> incrby t2:v3 3
(integer) -2

127.0.0.1:6379> incr t2:v4  <-- 없는 key인 t2:v4 값을 증가 시키니, key를 생성하고 1 값을 세팅
(integer) 1

127.0.0.1:6379> mget t2:v1 t2:v2 t2:v3 t2:v4
1) "2"
2) "-1"
3) "-2"
4) "1"

127.0.0.1:6379> decrby t2:v4 3      1 -   2 = -1
(integer) -2

127.0.0.1:6379> decrby t2:v4 -3    -2 - (-2) = 1
(integer) 1

 

   1.3 Bit 데이터 처리

        1) 비트 연산을 통해 저장되는 문자열 데이터를 비트 단위로 처리
        2) 
strlen 키에 저장된 문자열의 크기를 리턴 (문자열길이/8 +1)

setbit key offset value

getbit key offset

 

127.0.0.1:6379> setbit testbit 255 1     <-- testbit key의 255번째 자리에 1 값을 설정
(integer) 0

127.0.0.1:6379> setbit testbit 260 0     <-- testbit key의 260번째 자리에 0 값을 설정
(integer) 0

127.0.0.1:6379> getbit testbit 255
(integer) 1

127.0.0.1:6379> getbit testbit 260
(integer) 0

127.0.0.1:6379> getbit testbit 259       <-- 설정 되지 않은 key값은 0을 반환 
(integer) 0

127.0.0.1:6379> strlen testbit           testbit key에 저장된 문자열의 길이를 반환
(integer) 33

127.0.0.1:6379> setbit testbit 400 1
(integer) 0

127.0.0.1:6379> getbit testbit 400
(integer) 1

127.0.0.1:6379> strlen testbit
(integer) 51

127.0.0.1:6379> setbit testbit 401 a    0/1 이 아닌 다른 값을 입력하면 에러
(error) ERR bit is not an integer or out of range

 

        3) bitcount 명령은 비트가 1 설정  것만 카운트

127.0.0.1:6379> bitcount testbit
(integer) 2

 

   1.4 Hash 데이터 처리 ( = database의 table과 비슷 )

        1) 해시 데이터는 문자열 필드와 값의  구조로, 테이블과 가장 유사 (2^32 -1필드&값 저장)
        2) key
 하나가 여러개의 필드-값의 조합으로 이루어 진다.
           
key --- field1---value1
               
 --- field2---valeu2
               
 --- field3---value3

hset key field value  필드 추가       

hmset key field value [field value ...]  여러 개의 필드 추가

hget key field   피드  조회

hmget key field [field ...]  여러 개의 필드  조회

hlen key  필드 개수 조회

hgetall key  모든 필드 명과  조회

hkeys key   필드 명만 조회

hvals key   필드 명을 제회한 전체 값만 조회

 

hincrby key field increment       필드 값이 숫자일 경우 , (해당 필드가 없을 경우 생성 하고 값을 추가 )

hincrbyfloat key field increment  필드 값이 숫자일 경우 , (해당 필드가 없을 경우 생성 하고 값을 추가 )

 

127.0.0.1:6379> hmset bstar:info name ""  Birth 1975.01.11 Sex M Region Seoul RegDate 2017.10.03
OK

127.0.0.1:6379> hlen bstar:info                  <-- 키에 들어있는 필드 개수 리턴
(integer) 5

 

127.0.0.1:6379> hmget bstar:info name Birth  
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) "1975.01.11"

127.0.0.1:6379>hmget bstar:info name Birth Sex Region RegDate
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) "1975.01.11"
3) "M"
4) "Seoul"
5) "2017.10.03"

127.0.0.1:6379> hset bstar:info Sex F
(integer) 0

127.0.0.1:6379>hmget bstar:info name Birth Sex Region RegDate
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) "1975.01.11"
3) "F"
4) "Seoul"
5) "2017.10.03"

127.0.0.1:6379> hsetnx bstar:info Sex M     <-- Sex 필드가 존재 하므로 에러 발생
(integer) 0

127.0.0.1:6379> hmget bstar:info name Birth Sex Region RegDate
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) "1975.01.11"
3) "F"
4) "Seoul"
5) "2017.10.03"

127.0.0.1:6379> hdel bstar:info Birth     <-- Birth 필드 삭제
(integer) 1

127.0.0.1:6379> hmget bstar:info name Birth Sex Region RegDate
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) (nil)
3) "F"
4) "Seoul"
5) "2017.10.03"

127.0.0.1:6379> hlen bstar:info
(integer) 4

127.0.0.1:6379> hincrby bstar:info LoginCnt 1  <-- 없는 Field LoginCnt가 추가 되므로 필드가 추가되고 값이 추가됨
(integer) 1

127.0.0.1:6379> hmget bstar:info name Birth Sex Region RegDate LoginCnt
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) (nil)
3) "F"
4) "Seoul"
5) "2017.10.03"
6) "1"

127.0.0.1:6379> hincrbyfloat bstar:info LoginCnt 1.5
"2.5"

127.0.0.1:6379> hmget bstar:info name Birth Sex Region RegDate LoginCnt
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) (nil)
3) "F"
4) "Seoul"
5) "2017.10.03"
6) "2.5"

127.0.0.1:6379> hincrbyfloat bstar:info LoginCnt -1    <-- 정수를 사용해도 됨
"1.5"

127.0.0.1:6379> hmget bstar:info name Birth Sex Region RegDate LoginCnt
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) (nil)
3) "F"
4) "Seoul"
5) "2017.10.03"
6) "1.5"

127.0.0.1:6379> hgetall bstar:info
 1) "name"
 2) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
 3) "Sex"
 4) "F"
 5) "Region"
 6) "Seoul"
 7) "RegDate"
 8) "2017.10.03"
 9) "LoginCnt"
10) "1.5"

127.0.0.1:6379> hkeys bstar:info    <-- 해시테이블에 있는 필드 명 조회
1) "name"
2) "Sex"
3) "Region"
4) "RegDate"
5) "LoginCnt"

127.0.0.1:6379> hvals bstar:info   <-- 해시테이블에 있는 값 조회
1) "\xec\xb5\x9c\xec\x98\x81\xec\xa4\x80"
2) "F"
3) "Seoul"
4) "2017.10.03"
5) "1.5"

 

   1.5 SET 데이터 처리 ( = java의 List와 비슷 )

        1) 중복을 허용하지 않는 집합 형태의 자료 구조, 정렬되어 있지 않다. (2^32 -1  저장)
           정렬되어질 필요가 있을 경우 SORTED SET 사용
           값이 중복되어 저장되지 않으므로 nx 접미사의 명령어가 필요 없음
        2) 
SET 데이터는 하나의 Key 여러 개의 (member) 저장되며집합 연산이 가능

집합 연산은 합집합(Sunion), 교집합(Sinter), 차집합(Sdiff) 

sadd key member [member ...]     Key Value 추가 (추가 성공  1 리턴)

smembers key                     Key 들어있는 값을 모두 조회 

srem key member [member ...]     Key에서 Value 삭제(삭제 성공  1 리턴)

scard key                        key 들어 있는 value 개수 조회 (card  Cardinality 약어)

spop key [count]                 들어 있는 value 추출하고 삭제 한다.

sismember key member             Value 조회 하는 값이 있으면 1 리턴 하고, 없으면 0 리턴 

 

sunion key [key ...]             합집합

sinter key [key ...]             교집합

sdiff key [key ...]              차집합

 

SET 타입 문자열 비교

127.0.0.1:6379> sadd Test:Info:Site 'www.naver.com' 'www.google.com' 'www.daum.net' 'www.korea.com'
(integer) 4

127.0.0.1:6379> smembers Test:Info:Site
1) "www.naver.com"
2) "www.daum.net"
3) "www.korea.com"
4) "www.google.com"

127.0.0.1:6379> sismember Test:Info:Site 'www.naver*'   (일치하는 문자열 검색/ 없으면 0 있으면 1)
(integer) 0

127.0.0.1:6379> sismember Test:Info:Site 'www.naver.com'
(integer) 1

127.0.0.1:6379> sscan Test:Info:Site 0 match '*naver*'  (Like 검색 )
1) "0"
2) 1) "www.naver.com"

127.0.0.1:6379> sscan Test:Info:Site 0 match '*com*'
1) "0"
2) 1) "www.naver.com"
   2) "www.korea.com"
   3) "www.google.com"

 

127.0.0.1:6379> sadd bstar:Url google.com naver.com champstudy.com pass.com daum.net
(integer) 0

127.0.0.1:6379> smembers bstar:Url
1) "google.com"
2) "champstudy.com"
3) "daum.net"
4) "naver.com"
5) "pass.com"

127.0.0.1:6379> scard bstar:Url
(integer) 5

127.0.0.1:6379> sadd content1:Url champstudy.com
(integer) 0

127.0.0.1:6379> sadd content1:Url daum.net
(integer) 0

127.0.0.1:6379> scard content1:Url
(integer) 2

127.0.0.1:6379> sinter bstar:Url content1:Url
1) "champstudy.com"
2) "daum.net"

127.0.0.1:6379> sunion bstar:Url content1:Url
1) "pass.com"
2) "champstudy.com"
3) "google.com"
4) "daum.net"
5) "naver.com"

127.0.0.1:6379> sdiff bstar:Url content1:Url
1) "google.com"
2) "naver.com"
3) "pass.com"

127.0.0.1:6379> sdiff  content1:Url bstar:Url
(empty list or set)

127.0.0.1:6379> srem bstar:Url daum.net
(integer) 1

127.0.0.1:6379> scard bstar:Url
(integer) 4

127.0.0.1:6379> sinter bstar:Url content1:Url
1) "champstudy.com"

127.0.0.1:6379> sadd bstar:Url google.com naver.com champstudy.com pass.com daum.net
(integer) 5

127.0.0.1:6379> spop bstar:Url 4     <--- bstar:Url에서 4개의 값을 보여주고 삭제
1) "naver.com"
2) "pass.com"
3) "champstudy.com"
4) "google.com"

127.0.0.1:6379> scard bstar:Url
(integer) 1

127.0.0.1:6379> spop bstar:Url 4     <-- 4개의 값을 빼서 보여줘야 하는데 1개 밖에 남아 있지 않음
1) "daum.net"

127.0.0.1:6379> scard bstar:Url
(integer) 0

127.0.0.1:6379> sadd bstar:Url google.com naver.com champstudy.com pass.com daum.net
(integer) 5

127.0.0.1:6379> spop bstar:Url 2
1) "daum.net"
2) "google.com"

127.0.0.1:6379> spop bstar:Url 2
1) "pass.com"
2) "naver.com"

127.0.0.1:6379> spop bstar:Url 2
1) "champstudy.com"

127.0.0.1:6379> spop bstar:Url 2
(empty list or set)

127.0.0.1:6379> sadd bstar:Url google.com naver.com champstudy.com pass.com daum.net
(integer) 5

127.0.0.1:6379> sismember bstar:Url google.com
(integer) 1

127.0.0.1:6379> sismember bstar:Url google.co.kr
(integer) 0

127.0.0.1:6379> sismember bstar:Url google
(integer) 0

 

   1.6 SORTED SET 데이터 처리

        1) 정렬된 SET 데이터로써 가중치를 줘서 정렬접두사로 z 사용한다. (z = sorted)
        2) 
기본 정렬은 오름차순 정렬(zrange) 이고, 내림차순 정렬(zrevrange)도 있음
        3) 
WITHSCORES 명령어를 함께 사용하면 가중치 값도 같이 조회   있다.

zadd key [NX|XX] [CH] [INCR] score member [score member ...]    value 추가

zrevrange key start stop [WITHSCORES]                           내림차순 정렬

zrange key start stop [WITHSCORES]                              오름차순 정렬

zincrby key increment member                                    해당 멤버의 가중치  증감

zscore key member                                               해당 멤버의 가중치  조회

zrank key member                                                해당 멤버의 오름차순 순서

zrevrank key member                                             해당 멤버의 내림차순 순서

 

127.0.0.1:6379> zadd SsetTest 1 value1 3 value3 5 value5
(integer) 3

127.0.0.1:6379> zrange SsetTest 1 100     1 < 가중치 <= 100 오름차순 조회
1) "value3"
2) "value5"

127.0.0.1:6379> zrange SsetTest 1 100 withscores   가중치 정보 까지 조회
1) "value3"
2) "3"
3) "value5"
4) "5"

127.0.0.1:6379> zrevrange SsetTest 1 100           내림차순 조회
1) "value3"
2) "value1"

127.0.0.1:6379> zrevrange SsetTest 1 100 withscores
1) "value3"
2) "3"
3) "value1"
4) "1"

127.0.0.1:6379> zadd SsetTest 10 value5  <--- value5의 가중치를 10으로 변경
(integer) 0

127.0.0.1:6379> zrange SsetTest 0 10 withscores
1) "value1"
2) "1"
3) "value3"
4) "3"
5) "value5"
6) "10"

127.0.0.1:6379> zincrby SsetTest 1 value5
"11"

127.0.0.1:6379> zrank SsetTest value1
(integer) 0

127.0.0.1:6379> zrank SsetTest value3
(integer) 1

127.0.0.1:6379> zrank SsetTest value5
(integer) 2

127.0.0.1:6379> zrevrank SsetTest value5
(integer) 0

127.0.0.1:6379> zrevrank SsetTest value3
(integer) 1

127.0.0.1:6379> zrevrank SsetTest value1
(integer) 2

 

--[ Sorted Set을 이용한 성적 관리  (국어 성적/영어 성적) ]-----------------------------------------------

127.0.0.1:6379> zadd Class1:Korean 80 criss 95 hana 100 joon 100 young 90 Dong 85 hyun 70 Kim
(integer) 7

127.0.0.1:6379> zadd Class1:English 92 criss 100 hana 70 joon 92 young 80 Dong 90 hyun 90 Kim
(integer) 7

--[ criss의 국어와 영어 성적 조회 ]--------------------------------------------------------------------------

127.0.0.1:6379> zscore Class1:Korean criss
"80"

127.0.0.1:6379> zscore Class1:English criss
"92"

--[ criss의 국어/영어 성적 등수 ]----------------------------------------------------------------------------

127.0.0.1:6379> zrevrank Class1:Korean criss
(integer) 5

127.0.0.1:6379> zrevrank Class1:English criss
(integer) 2

--[ 국어 성적이 90점 이상 인 학생들 확인 ]----------------------------------------------------------------

127.0.0.1:6379> zrevrangebyscore Class1:Korean 100 90
1) "young"
2) "joon"
3) "hana"
4) "Dong"

127.0.0.1:6379> zrevrangebyscore Class1:Korean 100 90 withscores
1) "young"
2) "100"
3) "joon"
4) "100"
5) "hana"
6) "95"
7) "Dong"
8) "90"

 

   1.7 LIST 데이터 처리

        1) 저장된 순서를 기억하는 데이터 구조로, 중복을 허용 (저장 가능한 값은 2^32 =  42억개)
        2) 
헤드는 리스트의 첫번  요소 이며, 테일은 리스트의 마지막 요소
        3) 
데이터를 넣을  왼쪽으로 넣을지 오른쪽으로 넣을지에 따라서 lpush(Left Push), rpush(Right Push)명령사용
            stack 
= 먼저 들어간 것이 제일 마지막에 처리되며제일 마지막에 입력  것이 제일 먼저 처리
            queue = 
입력과 출력 방향이 달라서 보통 말하는 선입 선출
            deck = 
LIST 데이터는 입력도 양쪽으로 가능하고출력도 양쪽으로 가능한 구조
        4) 
입력은 push, 출력은 pop이다. 왼쪽 = "l", 오른쪽 = "r"  접두사
        5) 
pop 명령은 해당 데이터를 조회 하면서 제거 한다.

127.0.0.1:6379> lpush List:test value1 value2 value3 value4
(integer) 4

127.0.0.1:6379> rpush List:test value8 value7 value6 value5
(integer) 8

데이터가 들어가는 순서는
value4 --> value3 --> value2 --> value1 --> 순으로 왼쪽에서 들어가, 마지막에 들어가는 value4 제일 왼쪽의 데이터

<-- value8 <-- value7 <-- value6 <-- value5 순으로 오른쪽에서 들어가, 마지막에 들어가서
제일 오른쪽에 위치하는 값은 value5 된다.

127.0.0.1:6379> lindex List:test 0
"value4"

127.0.0.1:6379> lindex List:test 1
"value3"

127.0.0.1:6379> lindex List:test 2
"value2"

127.0.0.1:6379> lindex List:test 3
"value1"

127.0.0.1:6379> lindex List:test 4
"value8"

127.0.0.1:6379> lindex List:test 5
"value7"

127.0.0.1:6379> lindex List:test 6
"value6"

127.0.0.1:6379> lindex List:test 7
"value5"

127.0.0.1:6379> lindex List:test 8
(nil)

127.0.0.1:6379> lindex List:test -1
"value5"

127.0.0.1:6379> rpop List:test       <-- 가장 오른쪽에 있는 값을 조회
"value5"

127.0.0.1:6379> lindex List:test 7   <-- 조회한 데이터가 없어
(nil)

127.0.0.1:6379> rpop List:test 6    <-- 해당 인덱스의 값을 조회
1) "List:test"
2) "value6"

127.0.0.1:6379> lindex List:test 6
(nil)

127.0.0.1:6379> lrange List:test 0 10  <-- 해당 리스트의 값을 조회 0-10번 인덱스 까지 조회
1) "value4"
2) "value3"
3) "value2"
4) "value1"
5) "value8"
6) "value7"