【redis】python 操作redis

python 操作redis集群

一、redis的单实例进行连接操作

根据不同的实例方法,与redis的命令对应
python3
>>>import redis
>>>r = redis.StrictRedis(host='localhost', port=6379, db=0,password='root')
>>>r.set('lufei', 'guojialei')
True
>>>r.get('lufei')
b'guojialei'
注意事项:密码:端口要一致,数据库是否启动,没有的参数可以不写
增删改查 >>> 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()
[]

 二、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

 三、python连接rediscluster集群测试

模块安装注意事项:
pip3 install redis-py-cluster
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

4.1安装模块

 pip3 install django-redis-sessions
或者
pip3 install django-redis

 

4.2djanjo实例

1、修改settings配置文件

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'

 

2、创建djanjo应用

django-admin startapp app01

 

3、编写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))

 

4、添加url路由

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),
]

 

5、启动reis服务端

redis-server &

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

 

6、启动django

python3 manage.py runserver 0.0.0.0:8000

 

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

8、访问视图,获取session信息

 

9、检查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-07-05 22:04  与凯学习  阅读(193)  评论(0编辑  收藏  举报