rate-limit-redis 라이브러리를 뜯어보며

00_8_3·2023년 3월 17일
0

오픈소스 해부

목록 보기
1/2

rate-limit-redis

rate-limit-redis 라이브러리는 express-rate-limit의 memoryStore에 사용된다.

해당 라이브러리 코드를 보면 sendCommand 함수를 많이 사용하는데

1 sendCommand

  • sendCommand는 store의 메서드이다.
  • Redis에 직접 명령어를 보내는 함수이다.
redisClient.sendCommand(command: string, args?: any[], callback?: Function): boolean;
  • Lua 스크립트를 사용해 메서드를 저장하고(sha 반환) 메서드를 실행 할 수 있다.

sql의 프로시저와 비슷함.

2 로드와 실행

  • 내부 코드
const result = await this.sendCommand(
      "SCRIPT",
      "LOAD",
      `
        local totalHits = redis.call("INCR", KEYS[1])
        local timeToExpire = redis.call("PTTL", KEYS[1])
        if timeToExpire <= 0 or ARGV[1] == "1"
        then
            redis.call("PEXPIRE", KEYS[1], tonumber(ARGV[2]))
            timeToExpire = tonumber(ARGV[2])
        end
        return { totalHits, timeToExpire }
    `
        // Ensure that code changes that affect whitespace do not affect
        // the script contents.
        .replace(/^\s+/gm, "")
        .trim()
    );

위 처럼 load가 완료 후
EVALSHA와 반환된 sha를 사용하면된다.

const results = await this.sendCommand(
      "EVALSHA",
      await this.loadedScriptSha1, // 여기가 위 로드된 sha
      "1",
      this.prefixKey(key),
      this.resetExpiryOnChange ? "1" : "0",
      this.windowMs.toString()
    );

EVALSHA와 LOAD SCRIPT는 엔터프라이즈 2.6.0 이후 사용가능하다.

3 ARGV[1]

  • ARGV1은 lua 스크립트를 실행할 때 전달되는 두 번째 인자

  • 위 코드에서는 this.prefixKey(key),를 의미한다.

4 INCR

  • 키 값을 +1 증가

5 PTTL

  • PTTL은 키가 만료되기까지 남은 밀리초를 반환하는 명령어
  • 만약 키가 존재하지 않거나 만료 시간이 없으면 -1을 반환하고, 이미 만료된 키면 -2를 반환

6 PEXPIRE

  • PEXPIRE는 키에 밀리초 단위로 만료 시간을 설정하는 명령어

참고

http://redisgate.kr/redis/command/lua_evalsha.php

0개의 댓글