本文部分翻译自《Redis in Action》(Josiah L Carlson)。
之前,我们利用ZSET建立了一张城市ID与起始IP地址的对应表。要查询一个IP,我们首先需要使用与之前一样的办法,即将IP转换为10进制整数。之后找到比该IP值相等或较小的最大起始IP。
之前已经提到,之所以用到ZSET,就是方便这里的查询。即我们可以利用ZREVRANGEBYSCORE,通过传递START=0,NUM=1,从而实现预想的查询方法。正确获取城市ID后,我们再利用ID到城市ID与信息映射表(HASH)中查询到对应的城市信息。
具体的实现代码如下:
def find_city_by_ip(conn, ip_address): if isinstance(ip_address, str): ip_address = ip_to_score(ip_address) city_id = conn.zrevrangebyscore( 'ip2cityid:', ip_address, 0, start=0, num=1) if not city_id: return None city_id = city_id[0].partition('_')[0] return json.loads(conn.hget('cityid2city:', city_id))
了解更多,可以参看Josiah L Carlson的《Redis in Action》这本书。