Redis - minnie0531/fastapi-template GitHub Wiki

(under constuction)

Redis란?

Redis는 Remote의 in-memory data sotre 이다.
key-value기반의 noSQL이며, DB cache, Publish/Subscribe messaging system 의 목적으로 많이 사용된다.
In-memory여서 사용되는 예는 매우 많은데 랭킹, 세션 스토어, 스트리밍, Machine Learning 등 다양한 곳에 사용된다.

Data type

redis 는 key-value 형태의 데이터를 저장소이지만 비단 string뿐 아니라 다양한 데이터를 사용할 수 있다.
문자열(string)
해시(hashes)
리스트(list)
집합(sets)
정렬된 집합(sorted sets)
비트맵(bitmap)
하이퍼로그 로그(hyperloglog)
지리공간 인덱스(geospatial indexes)
스트림(streams)

Commands

redis에서는 각 data type에 맞는 command를 이용하여 데이터를 저장하거나 갖고 온다.

String을 예를 들면 다음과 같은 커맨드를 사용하여 데이터를 저장, 가공, 추출 한다.
ex) APPEND, GET, INCR, MGET, MSET, SET etc..
그 외 내용에 대해서는 아래 페이지와 오른쪽의 연관 command를 확인 하면 된다.
https://redis.io/commands/get

Hashmap의 경우는 다음과 같다.

HDEL, HEXISTS, HGET, HGETALL, HINCRBY, HINCRBYFLOAT, HKEYS, HLEN, HMGET, HMSET, HRANDFIELD, HSCAN, HSET, HSETNX, HSTRLEN, HVALS
자세한 내용은 아래 페이지와 연관 command를 확인 하면 된다.
https://redis.io/commands/hset

전체 command관련 해서는 아래 페이지를 참조 하면 된다.
https://redis.io/commands

Temporary store

아래 예제는 temporary data store로 데이터 저장 시 expire time을 설정하여 레디스에 저장하여 가져올 수 있도록 하는 방법이다. 데이터프레임을 pickle 을 이용하여 serialization한 다음 이를 저장한다. Deserialization을 할 때도 puckle을 이용하여 load한다.

import redis
import pandas as pd
import pickle
import time

r = redis.StrictRedis(host='localhost', port=6379, db=0)

@app.get("/redis")
async def test_redis():
    my_dict = {"a": ['1', '3'], "b": ['1', '2'], "c": ['2', '4']}
    p_mydict = pickle.dumps(my_dict)
    r.set('mydict',p_mydict,ex=5)

    if r.exists("mydict"):
        read_dict = r.get('mydict')
        get_dic = pickle.loads(read_dict)
        logger.info("get dictionary from redis %s" % str(get_dic))
    else:
        #Add different behavior to do something instead of using redis
        logger.warn("there is no mydict in redis")
        
    time.sleep(10)

    if r.exists("mydict"):
        read_dict = r.get('mydict')
        get_dic = pickle.loads(read_dict)
    else:
        #Add different behavior to do something instead of using redis
        logger.warn("there is no mydict in redis")
    
    return get_dic
⚠️ **GitHub.com Fallback** ⚠️