安装库

pip install redis

连接

r = redis.StrictRedis(host='localhost',port=6379,db=0)
image.png

操作

字符串相关操作

  1. import redis
  2. class TestString(object):
  3. def __init__(self):
  4. self.r = redis.StrictRedis(host='localhost', port=6379)
  5. print(self.r)
  6. # 设置值
  7. def test_set(self):
  8. res = self.r.set('user1', 'juran-1')
  9. print(res)
  10. # 取值
  11. def test_get(self):
  12. res = self.r.get('user1')
  13. print(res)
  14. # 设置多个值
  15. def test_mset(self):
  16. d = {'user2': 'juran-2', 'user3': 'juran-3'}
  17. res = self.r.mset(d)
  18. # 取多个值
  19. def test_mget(self):
  20. l = ['user2', 'user3']
  21. res = self.r.mget(l)
  22. print(res)
  23. # 删除
  24. def test_del(self):
  25. self.r.delete('user2')

列表相关操作

  1. import redis
  2. class TestList(object):
  3. def __init__(self):
  4. self.r = redis.StrictRedis(host='localhost', port=6379)
  5. # 插入记录
  6. def test_push(self):
  7. res = self.r.lpush('common', '1')
  8. res = self.r.rpush('common', '2')
  9. # res = self.r.rpush('jr', '123')
  10. # 弹出记录
  11. def test_pop(self):
  12. res = self.r.lpop('common')
  13. res = self.r.rpop('common')
  14. # 范围取值
  15. def test_range(self):
  16. res = self.r.lrange('common', 0, -1)
  17. print(res)

集合相关操作

  1. import redis
  2. class TestList(object):
  3. def __init__(self):
  4. self.r = redis.StrictRedis(host='localhost', port=6379)
  5. # 添加数据
  6. def test_sadd(self):
  7. res = self.r.sadd('set01', '1', '2')
  8. lis = ['Cat', 'Dog']
  9. res = self.r.sadd('set02', lis)
  10. # 删除数据
  11. def test_del(self):
  12. res = self.r.srem('set01', 1)
  13. # 随机删除数据
  14. def test_pop(self):
  15. res = self.r.spop('set02')

哈希相关操作

  1. import redis
  2. class TestList(object):
  3. def __init__(self):
  4. self.r = redis.StrictRedis(host='localhost', port=6379)
  5. # 批量设值
  6. def test_hset(self):
  7. dic = {'id': 1, 'name': 'huawei'}
  8. res = self.r.hmset('mobile', dic)
  9. # 批量取值
  10. def test_hgetall(self):
  11. res = self.r.hgetall('mobile')
  12. # 判断是否存在 存在返回1 不存在返回0
  13. def test_hexists(self):
  14. res = self.r.hexists('mobile', 'id')
  15. print(res)