Python3学习(十):redis的连接和使用

1.reids的连接

Redis使用connection pool来管理对一个redis server 的所有连接,避免每次建立,释放连接的开销,默认,每个Redis实例都会维护一个自己的连接池。可以直接建立一个连接池,然后作为参数Redis,这样就可以实现多个Redis实例共享一个连接池。

import redis

try:
    #host is the redis host,the redis server and client are required to open, and the redis default port is 6379
    pool = redis.ConnectionPool(host='10.0.64.113', password = 'xxxxx', port=6379, db=3)
    print("connected success.")
except:
    print("could not connect to redis.")
r = redis.Redis(connection_pool=pool)

2.redis的简单使用

这里只介绍最基本的用法:将数据推送至redis的方法set,以及从redis取出数据的get。由于python3在redis中取出的数据是b'pythone',b代指二进制类型,所以还需要对redis进行相应的数据处理。

import redis
import re
try:
    #host is the redis host,the redis server and client are required to open, and the redis default port is 6379
    pool = redis.ConnectionPool(host='10.0.64.113', password = 'xxxxx', port=6379, db=3)
    print("connected success.")
except:
    print("could not connect to redis.")
r = redis.Redis(connection_pool=pool)

list = '300033,600066'
r.set('stock_codes', list)

list = str(r.get('stock_codes'))
list = re.findall(r"'(.+?)'", list)
list = "".join(list)  #atypical list -> str
list = list.replace(' ','')  #remove all spaces in str
list = list.split(",")  #str -> normal list

猜你喜欢

转载自blog.csdn.net/liao392781/article/details/80534618