python操作redis
直接上代码:(带认证密码的redis连接)
# 1、带认证密码。普通方式连接 import redis HOST = '192.168.1.123' PORT = '6379' POOL_NAME = 'redis_pool' PASSWORD = "123456" r = redis.StrictRedis(host=HOST, port=PORT, db=0, password=PASSWORD) r.set("foo", "bar") print(r.get("foo")) # 2、带认证密码。连接池方式连接 import redis HOST = '192.168.1.123' PORT = '6379' POOL_NAME = 'redis_pool' PASSWORD = "123456" pool = redis.ConnectionPool(host=HOST, port=PORT, db=0, password=PASSWORD) r = redis.Redis(connection_pool=pool) r.set('name', 'andy8888') print(r.get('name'))
安装redis
启动redis服务
安装python的支持包
用python代码操作redis
import redis r = redis.StrictRedis(host="localhost", port=6379, db=0) r.set("foo", "bar") print(r.get("foo"))
redis连接池
Redis 的连接池是多线程安全的、多进程安全的、自动重连的。
连接池的作用是当前连接断掉了自动重连。
你可以不用自己手动使用连接池。
不知道连接池之前:
redis使用的方法:
r=redis.StrictRedis(host=xxxx, port=xxxx, db=xxxx) r.xxxx()
有了ConnectionPool这个类之后,可以使用如下方法
pool = redis.ConnectionPool(host=xxx, port=xxx, db=xxxx) r = redis.Redis(connection_pool=pool)
这里Redis是StrictRedis的子类
推荐书写格式:常量-》代码
import redis # Redis Host REDIS_HOST = 'localhost' # Redis PORT REDIS_PORT = 6379 # 第几个redis库 REDIS_DB=0 # r = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) # r.set("foo", "bar2") # print(r.get("foo")) pool = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) r = redis.Redis(connection_pool=pool) r.set('name','andy8888') print(r.get('name'))
一个redis操作案例:读取文件数据,写入redis中
1.txt
a,b,c,d,mmm 1,2,3,4,55 aaa,bbb,ccc
run.py
import redis # Redis Host REDIS_HOST = 'localhost' # Redis PORT REDIS_PORT = 6379 # 第几个redis库 REDIS_DB = 1 POOL = redis.ConnectionPool(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB) 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) val = None if data_type.decode() == 'list': val = my_server.lrange(key, 0, -1) elif data_type == b'string': val = my_server.get(key) print("%s:%s" % (key, val)) if __name__ == '__main__': fileName = r'1.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())
输出结果
all data items number is b'3' [b'aaa', b'1', b'a', b'counter'] b'aaa':[b'aaa', b'bbb', b'ccc'] b'1':[b'1', b'2', b'3', b'4', b'55'] b'a':[b'a', b'b', b'c', b'd', b'mmm'] b'counter':b'3' None