#-*- coding: utf-8 -*-
'''
======================================================================
描述:python的redis连接操作案例
作者:xiawp
日期:2019/1/25 10:10:46
收获:引用redis模块连接redis服务。
通过 get()、set() 操作redis字符型数据;
通过 hset()、hget() 操作redis哈希类型数据
通过 json.dumps() 和 json.loads() 可以实现python中的字典数据的序列化和反序列化;
======================================================================
'''
import json
import redis
# decode_responses=True 设置响应数据自动解码,否则redis取出的数据都是 bytes 类型
localRedis = redis.Redis(host="127.0.0.1", port=6379, decode_responses=True)
# set字符型数据到redis
localRedis.set("testlocalhost", "127.0.0.1")
# python中的字典类型数据需要先通过 json.dumps 转换成字符串(json序列化操作)
localRedis.hset("testObject","001",json.dumps({"name":"张三" ,"year":1987, "city":"北京"}))
# 获取所有的key名
keyList = localRedis.keys()
# 遍历打印key对应value,通过get(key)不能获取字符存储类型以外的数据,因此需要加异常处理
for key in keyList:
print ("Type Of",type(key),"key = ",key,end=" , ")
try:
print ("value = ",localRedis.get(key))
except Exception as e:
print ()
print ("== redis.get(%s) 发生异常:"%(key),str(e))
# 通过 json.loads() 将json格式字符串数据转换成字典数据类型(json反序列化操作)
dirctObj = json.loads(localRedis.hget("testObject","001"))
print (dirctObj)
print ("001 的名字:", dirctObj["name"])
print ("\nThe End!")
'''
执行结果:
------------------------------------------------------------------------------------------------------------------------
---------- python ----------
Type Of <class 'str'> key = hellokey , value = helloTest....
Type Of <class 'str'> key = testlocalhost , value = 127.0.0.1
Type Of <class 'str'> key = testkey , value = test...
Type Of <class 'str'> key = testObject ,
== redis.get(testObject) 发生异常: WRONGTYPE Operation against a key holding the wrong kind of value
{'name': '张三', 'year': 1987, 'city': '北京'}
001 的名字: 张三
The End!
输出完成 (耗时 0 秒) - 正常终止
------------------------------------------------------------------------------------------------------------------------
'''