python操作redis集群

 

strictRedis对象方法用于连接redis

指定主机地址,port与服务器连接,默认db是0,redis默认数据库有16个,在配置文件中指定database 16

上代码

复制代码
1、对redis的单实例进行连接操作
根据不同的实例方法,与redis的命令对应
python3
>>>import redis
>>>r = redis.StrictRedis(host='localhost', port=6379, db=0,password='root')
>>>r.set('lufei', 'guojialei')
True
>>>r.get('lufei')
'bar'

增删改查

>>> conn=redis.StrictRedis()
>>>
>>>
>>> conn.set("name1","alex1")
True
>>> conn.set("name2","wupeiqi")
True
>>>
>>>
>>> conn.set("name1","alex666")
True
>>> conn.delete("name2","name1")
2

>>> conn.keys()
[b'name3', b'name2', b'name1']

--------------------

2、sentinel集群连接并操作


[root@db01 ~]# redis-server /data/6380/redis.conf
[root@db01 ~]# redis-server /data/6381/redis.conf
[root@db01 ~]# redis-server /data/6382/redis.conf 
[root@db01 ~]# redis-sentinel /data/26380/sentinel.conf &



--------------------------------
## 导入redis sentinel包
>>> from redis.sentinel import Sentinel  
##指定sentinel的地址和端口号
>>> sentinel = Sentinel([('localhost', 26380)], socket_timeout=0.1)  
##测试,获取以下主库和从库的信息
>>> sentinel.discover_master('mymaster')  
>>> sentinel.discover_slaves('mymaster')  
##配置读写分离
#写节点
>>> master = sentinel.master_for('mymaster', socket_timeout=0.1)  
#读节点
>>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)  
###读写分离测试   key     
>>> master.set('oldboy', '123')  
>>> slave.get('oldboy')  
'123'


----------------------
redis cluster的连接并操作(python2.7.2以上版本才支持redis cluster,我们选择的是3.5)
https://github.com/Grokzen/redis-py-cluster


3、python连接rediscluster集群测试
使用

python3
>>> from rediscluster import StrictRedisCluster  
>>> startup_nodes = [{"host": "127.0.0.1", "port": "7000"}]  
### Note: decode_responses must be set to True when used with python3  
>>> rc = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True)  
>>> rc.set("foo", "bar")  
True  
>>>   
'bar'
----------------------
复制代码

 redis存储session

django-redis-sessions 官方文档:https://pypi.org/project/django-redis-sessions/

dango-redis 官方文档:http://niwinz.github.io/django-redis/latest/#_configure_as_cache_backend

安装模块

安装模块
 pip3 install django-redis-sessions
或者
pip3 install django-redis

本文这里用的是django 2.0语法,创建django项目

django-admin startproject mydjango

修改settings.py文件

写入

复制代码
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": "redis://127.0.0.1:6379/0",
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "PASSWORD": "",
#             "PARSER_CLASS": "redis.connection.HiredisParser",
#             "SOCKET_TIMEOUT": 10,
#             "CONNECTION_POOL_CLASS_KWARGS": {
#                 "max_connections": 2,
#             }
        }
    }
}
  
#SESSION_COOKIE_AGE = 30 * 60 #设置session过期时间为30分钟
SESSION_ENGINE = 'django.contrib.sessions.backends.cache'
复制代码

创建app01

django-admin startapp app01

编写session视图函数 app01.views

复制代码
from django.shortcuts import render,HttpResponse

def set_session(request):
    request.session['username']='chaoge'
    request.session['age']=18
    return HttpResponse("设置sesson成功")

def get_session(request):
    username=request.session['username']
    age = request.session['age']
    return HttpResponse(username+":"+str(age))
复制代码

添加url路由

vim mydjango/urls.py

复制代码
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
    path('set_session/',views.set_session),
    path('get_session/',views.get_session),
    path('admin/', admin.site.urls),
]
复制代码

确保启动redis服务端,默认方式启动

redis-server &

redis-cli 连接无误
发送ping命令得到pong即可

启动django

python3 manage.py runserver 0.0.0.0:8000

访问视图,设置一条session信息,存入redis数据库

访问视图,获取session信息

检查redis数据库,是否存在一条key

复制代码
127.0.0.1:6379> keys *
1) ":1:django.contrib.sessions.cachep220moqvxclz2hyjqmbybqs3v8ck2i39"

获取这个key的值

127.0.0.1:6379> get :1:django.contrib.sessions.cachep220moqvxclz2hyjqmbybqs3v8ck2i39
"\x80\x04\x95!\x00\x00\x00\x00\x00\x00\x00}\x94(\x8c\busername\x94\x8c\x06chaoge\x94\x8c\x03age\x94K\x12u."

 
复制代码

 

posted @ 2019-06-08 20:21  7411  阅读(172)  评论(0编辑  收藏  举报