import redisclass RedisDB: def connectRedis(self): dbHost="localhost" port=6379 pwd='12345678' try: self.pool = redis.ConnectionPool(host=dbHost,port=port, db=0, password=pwd) print("connect redis ok") except : print("connect redis error") #set String def writeByString(self, key, value): r = redis.Redis(connection_pool=self.pool) r.set(key, value) #get String def readByString(self, key): r = redis.Redis(connection_pool=self.pool) return r.get(key) #set hash def writeByHash(self, key, field, value): r = redis.Redis(connection_pool=self.pool) return r.hset(key, field, value) #get hash def readByHash(self, key, field): r = redis.Redis(connection_pool=self.pool) return r.hget(key, field) #get all hash def readAllByHash(self, key): r = redis.Redis(connection_pool=self.pool) return r.hgetall(key) #set set def writeBySet(self,key, value): r = redis.Redis(connection_pool=self.pool) r.sadd(key,value) #get set def readBySet(self,key): r = redis.Redis(connection_pool=self.pool) return r.smembers(key) #diff set #在第一个name对应的集合中且不在其他name对应的集合的元素集合 def diffBySet(self,*args): r = redis.Redis(connection_pool=self.pool) return r.sdiff(*args) #set list def writeByList(self,key, *value): r = redis.Redis(connection_pool=self.pool) r.lpush(key, *value) #get list def readByList(self, key, start, end): r = redis.Redis(connection_pool=self.pool) return r.lrange(key, start, end) if __name__ == '__main__': redisdb_ = RedisDB() redisdb_.connectRedis() redisdb_.writeByString("test1",123) print(redisdb_.readByString("test1")) redisdb_.writeByHash("test2","age",13) redisdb_.writeByHash("test2","name","jack") print(redisdb_.readByHash("test2","name")) print(redisdb_.readAllByHash("test2")) redisdb_.writeBySet("test3","jack") redisdb_.writeBySet("test3","tom") redisdb_.writeBySet("test31","jack") redisdb_.writeBySet("test31","tom1") print(redisdb_.readBySet("test3")) print("diff:",redisdb_.diffBySet("test3","test31")) redisdb_.writeByList("test4","jack","tom") redisdb_.writeByList("test4","rose") print(redisdb_.readByList("test4",1,4))
Python访问Redis测试例子
时间:2023-04-23
相关推荐