python操作

安装依赖包

1
2
3
pip install redis
pip install django-redis
pip install redis-py-cluster

连接redis服务器

1
2
3
from redis import Redis

red = Redis(host="192.168.220.128", port=6379, password="123456")

操作方法

(偷懒贴一个连接在这里~)

http://t.zoukankan.com/davis12-p-14439690.html

写个例子:

1
2
3
4
5
//redis只支持string、int等基础类型,如果mysql数据库用到特殊类型需要额外进行转换
class User(models.Model):
name = models.CharField(max_length=20)
age = models.SmallIntegerField()
birth = models.CharField(max_length=10)
1
2
3
4
5
//在mysql中添加一些数据
User.objects.create(name="user1", age=18, birth=datetime.now())
User.objects.create(name="user2", age=18, birth=datetime.now())
User.objects.create(name="user3", age=18, birth=datetime.now())
User.objects.create(name="user4", age=18, birth=datetime.now())
1
2
3
4
5
//加入到redis中
users = User.objects.all()
for user in users:
user_hash = {'name': user.name, 'age': user.age, 'birth': user.birth}
red.hset('redisProj:' + 'user:' + str(user.id), mapping=user_hash)