首先要pip install redis
import redis,json
ip='211.149.218.16'
port=6379
db=0
passwd='123456'
r = redis.Redis(host=ip,port=port,db=db,password=passwd)#链接 redis
r.set('name','nhy')#如果key一样则冲掉原来的值
r.set('name',[1,2,3,4])
#r.set('name',{'name':'hehehe'})
name = r.get('name')
name.decode()#转成字符串,字符串类型,redis里面存的都是字符串,bytes类型的,要用decode()转成字符串
new_name = json.loads(name.decode())#用json转成list
print(name)
print(new_name)
print(type(new_name))
r.setex('nhy','lingyul',10)#设置key, value和失效时间秒
r.mset(name='hh',age='18')#批量set值,批量设置不能设置失效时间
print(r.keys('*n*'))#打印所有key
#哈希类型的key
r.hset('lingyul','user','lingyul')#r.hset('key','key','value')得到的结果是:
# row key value
# 1 user lingyul
print(r.hget('lingyul','user'))#单独获取指定的name的值
r.hgetall('lingyul')#全部获取
r.delete('key')#吧整个key都删掉
r.hdel('lingyul','user')#删除指定的key
r.set('user:lingyul','hahaha')#如果设置的key里面有冒号,则先建立冒号左边的为文件夹,文件夹下面有key和value,哈希类型也一样