django中创建cache.py,写如下代码
from redis import Redis
from django.conf import settings
class MSRedis(object):
'''读写分离客户端(只针对程序中用到的命令)'''
def __init__(self,conf):
self.master = Redis(**conf['Master'])
self.slave = Redis(**conf['Slave'])
self.read_commands = [
'ttl', 'exist', 'expire', 'get', 'keys',
'hget', 'hgetall', 'hkeys', 'hmget',
'sismember', 'smembers', 'sdiff', 'sinter', 'sunion'
'zrevrange', 'zrevrangebyscore', 'zrevrank', 'zscore'
]
def __getattribute__(self, name):
if name in ['master','slave', 'read_commands']:
return object.__getattribute__(self,name)
elif name in self.read_commands:
return self.slave.__getattribute__(name)
else:
return self.master.__getattribute__(name)
rds = MSRedis(settings.REDIS)
settings.py文件中添加配置:
REDIS = {
'Master':{
'host':'127.0.0.1',
'port': '6379',
'db': 1
},
'Slave':{
'host':'127.0.0.2',
'port': '6379',
'db': 1
},
}
然后django项目中用到redis的地方调用rds即可。