python 的 redis 库,连接池怎么用
发布网友
发布时间:2022-04-22 09:53
我来回答
共1个回答
热心网友
时间:2023-10-09 10:51
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import redis
host = r'localhost'
port = 6379
POOL = redis.ConnectionPool(host=host, port=port, db=0)
my_server = redis.Redis(connection_pool=POOL)
def read_in_data(file_name):
data = []
with open(file_name, 'r') as f:
for line in f:
line = line.strip()
data.append(line.split(','))
return data
def write_data_to_redis(data):
my_server.set('counter', 0)
for items in data:
my_server.incr('counter')
for item in items:
my_server.rpush(items[0], item)
def get_data_from_redis():
keys = my_server.keys()
for key in keys:
data_type = my_server.type(key)
if data_type == 'list':
val = my_server.lrange(key, 0, -1)
elif data_type == 'string':
val = my_server.get(key)
print "%s:%s" % (key, val)
if __name__ == '__main__':
fileName = r'/Users/qinchuanqing/Code/workspace/IMP/installation/storage/NeSchele.txt'
data = read_in_data(fileName)
write_data_to_redis(data)
print 'all data items number is %s' % my_server.get('counter')
print my_server.keys()
print get_data_from_redis()