python操作redis集群与Django中redis-session存储

python

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

  strictRedis对象方法用于连接redis

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

根据不同的实例方法,与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']

二、sentinel集群连接并操作

  2.1 环境搭建:

[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 &

  2.2 测试读写分离:

## 导入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'

  2.3 python连接rediscluster集群测试:

redis cluster的连接并操作(python2.7.2以上版本才支持redis cluster,我们选择的是3.5)

https://github.com/Grokzen/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

>>> rc.set("foo", "bar")
'bar'


补充:rediscluster 安装方式:

   pip3 install redis-py-cluster 

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

  3.1 安装模块:

#安装模块

pip3 install django-redis-sessions

#或者

pip3 install django-redis

  3.2 创建django项目:

django-admin startproject mydjango

  3.3 修改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'

  3.4 创建app01:

django-admin startapp app01

  3.5 编写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))

  3.6 添加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),

]

  3.7 启动redis服务端,默认方式启动:

#& 把redis任务放在后台运行
redis-server &

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

  3.8 启动django:

python3 manage.py runserver 0.0.0.0:8000

  3.9 web窗口调试:

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

  

  访问视图,获取session信息

  

  3.10 redis-cli客户端测试:

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

#查看存在的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."

以上是 python操作redis集群与Django中redis-session存储 的全部内容, 来源链接: utcz.com/z/387058.html

回到顶部