Redis-Python Api

作者: Chris0Yang | 来源:发表于2021-07-28 17:16 被阅读0次

    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
    

    添加 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数据库

    image.png

    访问视图,获取session信息

    image.png

    检查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."
    

    相关文章

      网友评论

        本文标题:Redis-Python Api

        本文链接:https://www.haomeiwen.com/subject/vwyzmltx.html