私が正しく理解している場合、私がお勧めするもの(可能であれば)は、鍵のフォーマットを少し変更することです。一般的なmymsgs
をキーとして使用する代わりに、キー自体にホスト名を何らかの形で追加することをお勧めします。たとえば、mysgs_from_HOSTNAME
とすることができます。あなたはすべてメッセージを取得したいときは、キーを取得するために、ワイルドカードを使用することができますので
、あなただけmysgs_from_*
に一致するキーの一覧を表示し、それらのキーの値を得ることができます。あなたはHOSTNAME
と呼ばれるホスト名がダウンしていることを知ったときにそのように、あなたはすぐに行うことで、そのすべてのエントリを削除できdelete("mysgs_from_HOSTNAME"
) `
この例を参照してください:
import redis
import time
import pickle
redis_connection = redis.Redis(host='localhost', port=6379, db=0)
# This "for" loop is just a simple populator, to put a bunch of key/values in Redis
for hostname in ['abc1', 'foo2', 'foo3']:
msg = {'hostname': hostname, 'version': 'foo', 'uptime': 'bar'}
# Step 1, store the data using a key that contains the hostname:
redis_key = "messages_from_host_%s" % hostname
redis_connection.zadd(redis_key, pickle.dumps(msg), int(time.time() + 360))
# Ok... I have some sample data in Redis now...
# Shall we begin?...
# Let's say I wanna get all the messages from all the hosts:
# First, I find all the keys that can contain messages from hosts
matching_keys = redis_connection.keys("messages_from_host_*")
print "Got these keys that match what I wanna get: %s" % matching_keys
# Then I iterate through the keys and get the actual zrange (~value) of each
print "These are the messages from all those hosts:"
for matching_key in matching_keys:
messages = [pickle.loads(s) for s in redis_connection.zrange(matching_key, 0, -1)]
print messages
# Let's say that now, I discover that host called `foo2` is down, and I want
# to remove all its information:
redis_connection.delete("messages_from_host_foo2")
# All the entries referred to the host `foo2` should be gone:
print "Now, I shouldn't bee seing information from `foo2`"
matching_keys = redis_connection.keys("messages_from_host_*")
for matching_key in matching_keys:
messages = [pickle.loads(s) for s in redis_connection.zrange(matching_key, 0, -1)]
print messages
出力:
Got these keys that match what I wanna get: ['messages_from_host_foo2', 'messages_from_host_foo3', 'messages_from_host_abc1']
These are the messages from all those hosts:
[{'uptime': 'bar', 'hostname': 'foo2', 'version': 'foo'}]
[{'uptime': 'bar', 'hostname': 'foo3', 'version': 'foo'}]
[{'uptime': 'bar', 'hostname': 'abc1', 'version': 'foo'}]
Now, I shouldn't bee seing information from `foo2`
[{'uptime': 'bar', 'hostname': 'foo3', 'version': 'foo'}]
[{'uptime': 'bar', 'hostname': 'abc1', 'version': 'foo'}]
を
Redisキーに何らかの形でホスト名を追加できませんか?そうすれば 'hostname-foo *'のようなものを使うことができますか?または、時間をかけてキーを自動削除するタイマーがあれば、勉強することができますか? (私はhttp://redis.io/commands/expireを参照しています)? – BorrajaX
@BorrajaXだからここに事がある。私がRedisに保存しているデータは、ホスト名とその値がkvpとして格納された辞書の節約版です。私はそのようなレディスにとって新しいです。データストアから他の方法で削除する方法はありますか? – pypep278
あなたが 'kvp'と言うとき...それはレディスの鍵ですか? AFAIKでは、値ではなく、キーでのみワイルドカードを使用できます。あなたのキーはどのように見えますか?あなたは例を提供するために質問を編集できますか? – BorrajaX