Computer >> 컴퓨터 >  >> 프로그램 작성 >> 데이터 베이스

Redis에서 해시 사용

Redis에서 해시 사용

Redis의 해시는 필드와 값이 모두 문자열인 단일 키 아래에 연결된 필드-값 쌍을 저장하는 방법입니다. Redis는 전체 데이터 구조와 구조의 각 필드에 대한 수정을 허용합니다. 이것은 응용 프로그램의 개체를 위한 훌륭한(매우 빠른) 백업 저장소가 됩니다.

CLI 예제

두 개의 필드로 해시 생성:

127.0.0.1:6379> HMSET my_hash key1 "foo" key2 "bar"
OK

해시와 관련된 필드 및 값 나열:

127.0.0.1:6379> HGETALL my_hash
1) "key1"
2) "foo"
3) "key2"
4) "bar"

필드 중 하나의 값 업데이트:

127.0.0.1:6379> HSET my_hash key1 "xyzzy"
(integer) 0
127.0.0.1:6379> HGET my_hash key1
"xyzzy"

해시에서 단일 필드 삭제:

127.0.0.1:6379> HDEL my_hash key2
(integer) 1
127.0.0.1:6379> HGETALL my_hash
1) "key1"
2) "xyzzy"

해시 삭제:

127.0.0.1:6379> DEL my_hash
(integer) 1
127.0.0.1:6379> HGETALL my_hash
(empty list or set)

Redis의 우수한 문서에는 해시에 사용 가능한 명령에 대한 자세한 정보가 있습니다. 나는 당신을 위해 거기에서 복사/붙여넣기를 하지 않을 것입니다. 대신, 우리는 그들과 함께 약간의 재미를 가질 것입니다.

드웩시의 어레이!

Dwemthy's Array는 Why's (신렬한) Ruby 가이드에서 Why Lucky Stiff가 작성한 롤플레잉 게임(RPG)의 작은 예입니다. Ruby 메타프로그래밍을 설명하는 데 도움이 됩니다. 여기에서는 동일한 RPG 아이디어를 취하고 Redis 해시를 사용하여 구현합니다(Redis 배열의 약간의 도움으로).

다음과 같이 배열의 각 몬스터에 대한 해시를 생성합니다.

name: "AssistantViceTentacleAndOmbudsman"
life: 320
strength: 6
charisma: 144
weapon: 50

다음은 배열의 깊이에 대한 예제입니다.

>>> import redis
>>> import dwemthy
>>> conn = redis.StrictRedis(host="localhost", port=6379)
>>> dw = dwemthy.Array.new(conn,
      {
        "name": "AssistantViceTentacleAndOmbudsman",
        "life": 320,
        "strength": 6,
        "charisma": 144,
        "weapon": 50
      }
    )
"[Get ready. AssistantViceTentacleAndOmbudsman has emerged!]"
>>> rabbit = dwemthy.Rabbit(dw)
>>> rabbit.sword()
"[You hit with 2 points of damage!]"
"[Your enemy hit with 10 points of damage!]"
"[Rabbit has died!]"

따라하고 싶다면 전체 코드가 있습니다. dwemthy.py

코드 하이라이트

첫째, 사용자가 제공된 팩토리 메소드로 배열을 생성할 때 데이터 구조를 설정하고 새로운 dwemthy.Array 객체를 반환합니다:

class Array(object):
    list_key = "dwemethys_array"

    ...

    @classmethod
    def new(cls, conn, *bad_guys):
        """ Create a new set of problems for our hero to boomerang! """

        conn.delete(cls.list_key)

        # Give each bad guy a cozy spot in the array!
        for bad_guy in bad_guys:
            key = uuid.uuid4()
            conn.hmset(key, bad_guy)
            conn.rpush(cls.list_key, key)

        dw_list = cls(conn)
        dw_list.next_enemy()
        return dw_list

여기서 conn.hmset은 나쁜 사람에 대한 해시를 생성합니다. 그런 일이 발생하면 악의적인 사람의 키를 Redis 목록에 푸시하고 여기에서 간단한 대기열로 사용됩니다.

모든 나쁜 사람이 설정되면 Array.next_enemy() 메서드를 사용하여 배열의 선두에 있는 사람이 준비되었는지 확인합니다.

class Array(object):    
    list_key = "dwemethys_array"

    ...

    def next_enemy(self):
        """ Bring out the next enemy for our rabbit to face! """

        # We're moving on!
        if self.current != None:
            self.conn.delete(self.current)

        enemy_key = self.conn.lpop(self.list_key)

        if enemy_key is None:
            # Like a boss!
            print "[Whoa.  You decimated Dwemthy's List!]"
        else:
            # Get the new enemy ready!
            self.current = enemy_key
            print "[Get ready. {} has emerged!]".format(self["name"])

마지막 줄의 self["name"]은 배열 객체에 __setitem__ 및 __getitem__ 메서드를 정의하여 수행됩니다. 이렇게 하면 배열을 대부분 파이썬 딕셔너리로 ​​취급할 수 있으며 현재 나쁜 사람의 필드를 쉽게 가져오고 수정할 수 있습니다.

class Array(object):

    ...

    def __setitem__(self, key, value): 
        self.conn.hset(self.current, key, value)

    def __getitem__(self, key):
        value = self.conn.hget(self.current, key)

        # hashes only store strings!
        if key != "name":
            return int(value)

        return value

결론

Redis를 통해 해시를 수정할 수 있는 수많은 방법을 통해 개발자는 이를 사용하여 많은 문제를 해결할 수 있습니다. 이 게시물이 귀하의 프로젝트에 사용할 아이디어를 제공했기를 바랍니다.