REDIS 명령어 정리 :: 행복한 프로그래머

posted by 쁘로그램어 2019. 7. 24. 16:59

################################################

# redis-cli help

################################################

Usage: redis-cli [OPTIONS] [cmd [arg [arg ...]]]

  -h <hostname>      Server hostname (default: 127.0.0.1).

  -p <port>          Server port (default: 6379).

  -s <socket>        Server socket (overrides hostname and port).

  -a <password>      Password to use when connecting to the server.

                     You can also use the REDISCLI_AUTH environment

                     variable to pass this password more safely

                     (if both are used, this argument takes predecence).

  -u <uri>           Server URI.

  -r <repeat>        Execute specified command N times.

  -i <interval>      When -r is used, waits <interval> seconds per command.

                     It is possible to specify sub-second times like -i 0.1.

  -n <db>            Database number.

  -x                 Read last argument from STDIN.

  -d <delimiter>     Multi-bulk delimiter in for raw formatting (default: \n).

  -c                 Enable cluster mode (follow -ASK and -MOVED redirections).

  --raw              Use raw formatting for replies (default when STDOUT is

                     not a tty).

  --no-raw           Force formatted output even when STDOUT is not a tty.

  --csv              Output in CSV format.

  --stat             Print rolling stats about server: mem, clients, ...

  --latency          Enter a special mode continuously sampling latency.

                     If you use this mode in an interactive session it runs

                     forever displaying real-time stats. Otherwise if --raw or

                     --csv is specified, or if you redirect the output to a non

                     TTY, it samples the latency for 1 second (you can use

                     -i to change the interval), then produces a single output

                     and exits.

  --latency-history  Like --latency but tracking latency changes over time.

                     Default time interval is 15 sec. Change it using -i.

  --latency-dist     Shows latency as a spectrum, requires xterm 256 colors.

                     Default time interval is 1 sec. Change it using -i.

  --lru-test <keys>  Simulate a cache workload with an 80-20 distribution.

  --replica          Simulate a replica showing commands received from the master.

  --rdb <filename>   Transfer an RDB dump from remote server to local file.

  --pipe             Transfer raw Redis protocol from stdin to server.

  --pipe-timeout <n> In --pipe mode, abort with error if after sending all data.

                     no reply is received within <n> seconds.

                     Default timeout: 30. Use 0 to wait forever.

  --bigkeys          Sample Redis keys looking for keys with many elements (complexity).

  --memkeys          Sample Redis keys looking for keys consuming a lot of memory.

  --memkeys-samples <n> Sample Redis keys looking for keys consuming a lot of memory.

                     And define number of key elements to sample

  --hotkeys          Sample Redis keys looking for hot keys.

                     only works when maxmemory-policy is *lfu.

  --scan             List all keys using the SCAN command.

  --pattern <pat>    Useful with --scan to specify a SCAN pattern.

  --intrinsic-latency <sec> Run a test to measure intrinsic system latency.

                     The test will run for the specified amount of seconds.

  --eval <file>      Send an EVAL command using the Lua script at <file>.

  --ldb              Used with --eval enable the Redis Lua debugger.

  --ldb-sync-mode    Like --ldb but uses the synchronous Lua debugger, in

                     this mode the server is blocked and script changes are

                     not rolled back from the server memory.

  --cluster <command> [args...] [opts...]

                     Cluster Manager command and arguments (see below).

  --verbose          Verbose mode.

  --no-auth-warning  Don't show warning message when using password on command

                     line interface.

  --help             Output this help and exit.

  --version          Output version and exit.



################################################

# redis-cli 실행 및 기본 정보

################################################

# redis-cli 실행

$ redis-cli -p 6379

$ redis-cli -c -p 6379



-c(Enable cluster mode)는 cluster 모드 설정이다.

예를 들면 REDIS Master가 3대 있다고 가정하다.

REDIS1: 127.0.0.1 6379

REDIS2: 127.0.0.1 6380

REDIS3: 127.0.0.1 6381


-c로 접속해야 다른 노드에 있는 데이터를 조회할수 있다.

-c 옵션이 없으면 해당 노드에 대한 값만 조회된다.

Redirected 이후 127.0.0.1:6380>로 변경된다.


$ redis-cli -p 6379

127.0.0.1:6379> get 10:userprofile:1234

(error) MOVED 6537 127.0.0.1:6380


$ redis-cli -c -p 6379

127.0.0.1:6379> get 10:userprofile:1234

-> Redirected to slot [6537] located at 127.0.0.1:6380

127.0.0.1:6380>


# help

127.0.0.1:6379> help get


  GET key

  summary: Get the value of a key

  since: 1.0.0

  group: string


# info : Redis 서버 설정 정보를 확인

127.0.0.1:6379> info

# Server

redis_version:4.0.2

redis_git_sha1:00000000

redis_git_dirty:0


# monitor: REDIS 에서 수행되는 명령어를 실시간으로 모니터링한다.

127.0.0.1:6379> monitor

OK

1563949055.173437 [0 127.0.0.1:59130] "COMMAND"

1563949062.506209 [0 127.0.0.1:59130] "keys" "*"

1563949088.111414 [0 127.0.0.1:59134] "COMMAND"

1563949091.780905 [0 127.0.0.1:59134] "keys" "*"

1563949097.059684 [0 127.0.0.1:59134] "get" "tes


################################################

# CRUD 명령어

################################################

# keys : 현재의 키값 들을 확인하는 명령어

해당 명령어는 부하가 심하여 운영 중인 서비스에서는 절대 사용하면 안되는 명령어!!

127.0.0.1:6379> keys *

(empty list or set)


# set : 키/값을 저장하는 명령어

127.0.0.1:6379> set key value

127.0.0.1:6379> keys *

1) "key"


# mset: 여러개의 Key와 Value를 한번에 입력한다.


# setex: Key와 Value, Expires(sec) 설정을 입력한다.

(입력된 시간이후에 소멸한다.)



# get : 키에 해당하는 값을 가져오는 명령어.

127.0.0.1:6379> get key

"value"


# mget: 여러개의 Key값을 입력하여 Value를 동시에 리턴받는다.


# del : 키와 해당하는 값을 삭제하는 명령어. 여러개의 키값을 지우는 dels 가 없다

127.0.0.1:6379> del key

(integer) 1

127.0.0.1:6379> keys *

(empty list or set)


# Hash 구조체 : 하나의 Class 인스턴스 를 저장하기에 적당한 Redis 구조체는 hash 인거 같다.

Person 클래스

class Person {

    int id;

    string name;

    string pw;

    int uniqueNumber;

}



다음과 같이 person 인스턴스를 redis 에 저장하기 위해 hset(hmset) 을 이용한다.

Person person = 

    new Person { "id" = 1234, name = "tom", pw = "abcd5678", uniqueNumber = 56000 };


127.0.0.1:6379> hmset user id 1234 name tom pw abcd5678 uniqueNumber 56000;

OK


127.0.0.1:6379> hget user

(error) ERR wrong number of arguments for 'hget' command

127.0.0.1:6379> hmget user id

1) "1234"

127.0.0.1:6379> hgetall user

1) "id"

2) "1234"

3) "name"

4) "tom"

5) "pw"

6) "abcd5678"

7) "uniqueNumber"

8) "56000;"


http://redis.io/commands/hset

http://redis.io/commands/hmset



################################################

# 기타 명령어

################################################

save : 현재 데이터를 모두 저장

TTL: 키 값의 만료 시간이 몇 초 남았는지 확인

expire: 지정된 키에 만료시간을 초단위로 저장한다.

randomkey: 랜덤한 key return

rename: key의 이름 변경

ping: 연결이 유지되고 있는지 사용

exist: key가 존재하는지 확인

flushall: 데이터베이스에 있는 모든 key들을 삭제할 수 있다.

dbsize: 현재 사용중인(선택된) DB의 키 개수를 보여준다.

        레디스는 기본적으로 16개의 DB를 제공한다.

        DB 선택은 select index(숫자) 명령으로 할 수 있다.

CSV: 명령 실행 결과를 CSV(Comma Separated Values) 형태로 출력합니다.



################################################

# 기타 유용한 명령어 예시

################################################

# redis-cli로 COMMAND 실행

$ redis-cli -c -p 6379 keys "*"


# 레디스 서버의 중요 통계정보를 주기적보기

$ redis-cli -c -p 6379 --stat


# 시험용 명령 파일(1백만개 명령) 만들고 pipe로 로드하기

$ for i in {000000..999999}; do echo set key$i value$i >> data.txt; done

$ cat data.txt | redis-cli -p 6000 --pipe


# 여러 서버에 일괄 명령 실행하기

$ for i in {6001..6010}; do src/redis-cli -p $i dbsize; done


# 서버에서 실행되는 모든 명령을 관찰/감시

$ redis-cli -c -p 6381 monitor


# 현재 사용중인(선택된) DB의 키 개수 조회

$ redis-cli -c -p 6381 dbsize


# 모든 DB의 키 정보 조회

$ redis-cli -c -p 6381 info keyspace


# 레디스 서버의 모든 데이터(키와 값)를 삭제

$ flushall


# 현재 사용중인(선택된) DB의 모든 데이터(키와 값)를 삭제

$ flushdb



################################################

# 클러스터 관련 명령

################################################

127.0.0.1:6379> cluster info

127.0.0.1:6379> cluster nodes



################################################

# 참고사이트

################################################

http://redisgate.kr/redis/command/set.php#subquery

http://redisgate.jp/redis/server/redis-cli.php#stat

http://redisgate.jp/redis/server/server_cmd_intro.php

https://firstboos.tistory.com/entry/redis-%EA%B0%84%EB%8B%A8-%EB%AA%85%EB%A0%B9%EC%96%B4-%EC%A0%95%EB%A6%AC

http://wiki.pchero21.com/wiki/Redis_command

https://moss.tistory.com/entry/Redis-%EC%84%9C%EB%B2%84-%EC%84%A4%EC%A0%95-%EC%A0%95%EB%A6%AC

https://bcho.tistory.com/654

https://jojoldu.tistory.com/349

https://gist.github.com/gksxodnd007/5a04a0a387124faf548f46d8b9c16bfe

https://wedul.site/607

https://www.joinc.co.kr/w/man/12/REDIS/RedisWithJoinc/part02

http://www.dbguide.net/db.db?cmd=view&boardUid=186829&boardConfigUid=9&categoryUid=216&boardIdx=156&boardStep=1