Redis에는 value에 대해 많은 데이터 타입들이 존재합니다. set [key] [value]
꼴의 명령을 사용했던 것들은 value에 string이 사용되는데, 이번에는 push/pop을 사용하는 list
에 대해 알아보도록 합시다. list를 사용함으로써, redis를 queue처럼 활용할 수 있습니다.
List
List를 사용하면 sequence의 양 쪽 끝에서 요소를 push하고 pop하거나, 개별 요소를 가져오고 list에 수행할 수 있는 다양한 기타 작업을 수행할 수 있습니다. 아래는 가장 많이 사용되는 list 명령들입니다.
- rpush(rpush [key] [value ...]) : list의 오른쪽 끝에 value들을 추가합니다.
- lpush(lpush [key] [value ...]) : list의 왼쪽 끝에 value들을 추가합니다.
- rpop(rpop [key]) : list의 오른쪽 끝에서 요소 하나를 pop(제거하며 반환)합니다.
- lpop(lpop [key]) : list의 왼쪽 끝에서 요소 하나를 pop합니다.
- lindex(lindex [key] [offset]) : offset에 해당하는 요소를 반환합니다. zero-based numbring 방식을 따릅니다.
- lrange(lrange [key] [start] [end]) : start와 end 사이의 요소들을 모두 반환합니다.
- ltrim(ltrim [key] [start] [end]) : start와 end 사이의 요소들만 남도록 list를 잘라냅니다.
위의 명령어들을 사용한 예는 다음과 같습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
127.0.0.1:6379> lpush a 1 | |
(integer) 1 | |
127.0.0.1:6379> lpush a 2 | |
(integer) 2 | |
127.0.0.1:6379> rpush a 3 | |
(integer) 3 | |
127.0.0.1:6379> rpush a 4 | |
(integer) 4 | |
127.0.0.1:6379> lrange a 0 1 | |
1) "2" | |
2) "1" | |
127.0.0.1:6379> lrange a 0 -1 | |
1) "2" | |
2) "1" | |
3) "3" | |
4) "4" | |
127.0.0.1:6379> lindex a 3 | |
"4" | |
127.0.0.1:6379> lindex a -1 | |
"4" | |
127.0.0.1:6379> lpop a | |
"2" | |
127.0.0.1:6379> rpop a | |
"4" | |
127.0.0.1:6379> lrange a 0 -1 | |
1) "1" | |
2) "3" | |
127.0.0.1:6379> rpush a 3 | |
(integer) 3 | |
127.0.0.1:6379> rpush a 4 | |
(integer) 4 | |
127.0.0.1:6379> ltrim a 0 2 | |
OK | |
127.0.0.1:6379> lrange a 0 -1 | |
1) "1" | |
2) "3" | |
3) "3" |
lindex, lrange, ltrim 등 인덱스가 들어가는 곳에 음수가 들어갈 수 있다는 것을 알고 있으면 매우 유용합니다.
'데이터베이스 > Redis' 카테고리의 다른 글
[Redis] String(기본 조작) (0) | 2018.09.06 |
---|---|
[Redis] List의 고급 커맨드들 (0) | 2018.09.06 |
[Redis] select (0) | 2018.09.06 |
[Redis] Set (0) | 2018.09.06 |
[Redis] Publish/Subscribe (0) | 2018.09.06 |