본문 바로가기
프로그래밍/데이터베이스

C# redis에서 Key들을 pattern으로 조회하기

by bantomak 2023. 5. 25.

C# 프로젝트에서 redis를 사용하기 위해서 StackExchange.Redis 를 사용해서 구현하였다.

그리고 redis에서 pattern을 이용해서 key값들을 가져오는 함수 Keys()에 대해서 알아보자

함수 원형

// 요약:
//     Returns all keys matching pattern; the KEYS or SCAN commands will be used based
//     on the server capabilities; note: to resume an iteration via cursor, cast the
//     original enumerable or enumerator to IScanningCursor.
//
// 매개 변수:
//   database:
//     The database ID.
//
//   pattern:
//     The pattern to use.
//
//   pageSize:
//     The page size to iterate by.
//
//   cursor:
//     The cursor position to resume at.
//
//   pageOffset:
//     The page offset to start at.
//
//   flags:
//     The command flags to use.
//
// 설명:
//     Warning: consider KEYS as a command that should only be used in production environments
//     with extreme care.
IEnumerable<RedisKey> Keys(int database = -1, RedisValue pattern = default(RedisValue), int pageSize = 250, long cursor = 0L, int pageOffset = 0, CommandFlags flags = CommandFlags.None);

 

매턴 매칭

  • * : 모든 문자 매치 : h*llo -> hllo, heeeello 등등
  • ? : 1개 문자 매치 : h?llo -> hallo, hello, hxllo 등등
  • [alphabet] : 대괄호 안에 있는 문자 매치 : h[ae]llo -> hallo, hello
  • [^e] : 대괄호 안에 있는 문자 제외하고 매치 : h[^e]llo -> hallo, hbllo (hello는 제외됨)
  • [a-c] : 대괄호 안에 있는 문자 범위로 매치 : h[a-c]llo -> hallo, hbllo, hcllo
  • \(백슬래시) : 위에 사용한 특수문자(*?[^])를 사용하려면 앞에 \를 붙여서 사용: h\?llo -> h?llo

 

예제 코드

 

Keys() 함수에 패턴을 이용해서 RedisKey 리스트를 가져옴

해당 키들로 RedisValue 객체를 검색해서 가져온다. 이때 json Deerialize 과정이 필요함.

댓글