Redis JSON 모듈 적용

임재성·2024년 1월 2일
0

Redis

  • 외주 프로젝트를 진행하면서 Redis를 이용하여 데이터를 실시간으로 받아오는 부분이 존재하였으며, 데이터 형식은 JSON형식으로 정하였음.
  • 도커내부에서 Redis에 JSON을 사용하려고 하였음.
  • redislabs/rejson라는 이미지가 이미 JSON모듈을 포함하여 그대로 쓰면 되었지만 JSON모듈이 포함되지 않은 순수 redis 이미지에 어떻게 적용하는지가 궁금하여 잠깐 해보면서 정리한 내용.

Redis JSON

Redis에서는 JSON형태의 데이터를 저장할 수 있다.
데이터를 저장하는 방법은 python을 기준으로 json모듈의 dumps(), loads()를 사용하는 방법이고, redis 모듈의 json().set(), json().get() 을 사용하여 데이터를 저장하는 방식이다.

사용

  • python의 json 모듈을 사용하여 저장할 때는 단순히

    import redis
    import json
    r = redis.StrictRedis(host="localhost", port=6379, db=0)

    test_dict = {
    "T1": "test",
    "T2": ["data", "data2"]
    }

    json_dict = json.dumps(test_dict, ensure_ascii=False).encode('utf-8')
    r.set("test_dict", json_dict)

    json_test_dict = r.get('test_dict').decode('utf-8')
    test_dict2 = dict(json.loads(json_dict))

    print(test_dict2)

    와 같이 사용하면 된다.

  • redis 모듈의 json().set()의 경우

    import redis
    from redis.commands.json.path import Path

    r = redis.Redis(host='localhost', port=6379)

    r.json().set("user:1", Path.root_path(), user1)
    r.json().set("user:2", Path.root_path(), user2)
    r.json().set("user:3", Path.root_path(), user3)

    r.json().get("user:1")
    r.json().get("user:2")
    r.json().get("user:3")

    와 같은 방식으로 사용한다.

  • redis 서버에서는 json모듈이 설치되어 있어야 한다.

Redis JSON 모듈 설치

설치 (vm으로 linux 설치후 작업했음.)

  • 아래는
    Clone therepository(make sure you include the--recursiveoption to properly clone submodules):

    $ git clone --recursive https://github.com/RedisJSON/RedisJSON.git
    $ cd RedisJSON

    항목을 따라한 것이다.

  • Install dependencies:
    $ ./sbin/setup

  • Build:
    $ make build

  • 명령어 실행시 오류가 났다.

  • rustc와 cargo 명령어를 찾지 못했다..
    sudo apt install rustc
    sudo apt install cargo
    명령을 통해 설치를 해줬다..

  • 적용
    Redis에 모듈을 적용시킬 수 있는 방법이 2가지 있다.

    첫 번째, redis.conf 라는 redis의 설정파일을 이용하여 적용하는 방식인데,
    redis.conf에
    loadmodule librejson.so파일의 경로
    를 추가해주면 된다.

    두 번째, redis cli에서 직접 적용시키는 방법이다.
    redis-server --loadmodule librejson.so파일의 경로
    를 통해 레디스 서버 시작시 모듈을 적용시킬 수 있다.

  • 공식 문서 정보
    https://redis.io/docs/data-types/json/#configuration-file

profile
조금씩 앞으로

0개의 댓글