更新时间:2023-11-21 gmt 08:00

通过python连接实例-凯发k8国际娱乐官网入口

本章节主要介绍使用python访问geminidb redis实例的方法。

前提条件

  • 已成功创建geminidb redis实例,且实例状态为“正常”。
  • 已创建弹性云服务器,创建弹性云服务器的方法,请参见《弹性云服务器快速入门》中“”章节。
  • 弹性云服务器上已经安装gcc等编译工具。
  • 创建的弹性云服务器geminidb redis实例要保证区域、可用区、vpc和安全组一致。

操作步骤

  1. 获取geminidb redis实例的负载均衡地址和端口。
    • 负载均衡地址的查看方法请参见。
    • 端口信息的获取方法请参见。
  2. 登录弹性云服务器,具体操作请参见《弹性云服务器快速入门》中“”。
  3. 安装python和redis的python客户端redis-py。
    1. 如果系统没有自带python,可以使用yum方式安装。

      yum install python

    2. 下载并解压redis-py。

      wget https://github.com/andymccurdy/redis-py/archive/master.zip

    3. 进入到解压目录后安装redis的python客户端redis-py。

      python setup.py install

    4. 安装后执行python命令,返回如下信息说明成功安装redis-py:
      python 2.6.6 (r266:84292, aug 18 2016, 15:13:37) 
      [gcc 4.4.7 20120313 (red hat 4.4.7-17)] on linux2
      type "help", "k8凯发 copyright", "credits" or "license" for more information.
      >>> import redis
      >>> 
  4. 使用redis-py客户端连接geminidb redis实例。

    以下步骤以命令行模式进行示例(也可以将命令写入python脚本中再执行):

    • 使用单机方式连接geminidb redis集群
      1. 执行python命令,进入命令行模式。
        返回如下信息说明已进入命令行模式:
        python 2.6.6 (r266:84292, aug 18 2016, 15:13:37) 
        [gcc 4.4.7 20120313 (red hat 4.4.7-17)] on linux2
        type "help", "k8凯发 copyright", "credits" or "license" for more information.
        >>> import redis
        >>> 
      2. 在命令行中执行以下命令,确认结果正常。
        >>> r = redis.strictredis(host='192.xx.xx.xx', port=8635, password='pwd');
        >>> r.set('key', 'python tst ok!')
        true
        >>> r.get('key')
        'python tst ok!'

        如下信息请按照实际值进行修改后,再执行上述命令。

        • host和port为1中获取到的geminidb redis实例的负载均衡地址和端口。
        • password为geminidb redis实例的密码。
    • 使用集群方式连接geminidb redis集群
      使用前需要设置:config set compatiblemode clusterclient
      python 3.7.4 (default, jan 30 2021, 09:00:44) 
      [gcc 7.3.0] on linux
      type "help", "k8凯发 copyright", "credits" or "license" for more information.
      >>> from redis.cluster import rediscluster as redis
      >>> rc = redis(host='127.0.0.1', port=6379, password='a')
      >>> rc.set('key', 'python test ok!')
      true
      >>> rc.get('key')
      b'python test ok!'
分享:
网站地图