zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

Redis安装和操作

Redis安装 操作
2023-09-11 14:14:26 时间

任何技术栈,第一份资料首选,官方手册,没有比这更全,更准确

Redis数据库安装

参考学习链接:https://www.runoob.com/redis/redis-install.html

数据库下载地址:https://github.com/tporadowski/redis/releases

Redis管理工具安装

https://github.com/qishibo/AnotherRedisDesktopManager/blob/master/README.zh-CN.md
https://gitee.com/qishibo/AnotherRedisDesktopManager/releases
下载,然后双击安装即可
在这里插入图片描述

Redis运行在内存中但是可以持久化到磁盘

Redis运行在内存中但是可以持久化到磁盘,所以在对不同数据集进行高速读写时需要权衡内存,因为数据量不能大于硬件内存。在内存数据库方面的另一个优点是,相比在磁盘上相同的复杂的数据结构,在内存中操作起来非常简单,这样Redis可以做很多内部复杂性很强的事情。同时,在磁盘格式方面他们是紧凑的以追加的方式产生的,因为他们并不需要进行随机访问。

Redis python操作

官方api文档:https://redis.io/commands/
https://www.runoob.com/w3cnote/python-redis-intro.html

分隔符如果是:,当命名的时候就会按这个冒号,做目录分级,如果链接的时候,分隔符换成其他的,:冒号命名就不会目录分级
在这里插入图片描述
在这里插入图片描述

1、单个增加–修改(单个取出)–没有就新增,有的话就修改

注意hmset会在pycharm报已经删除的警告

用hset,设置mapping参数同样可以进行批量创建的

# -*- coding: utf-8 -*-

import redis
import time

pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=5)
r = redis.Redis(connection_pool=pool)
dcit_mart = {"k2": "v2", "k3": "v3"}
r.hset("hash2", mapping=dcit_mart)
print(r.hgetall('hash2'))
print(r.keys())  # 查询所有的Key
# r.delete("hash2")  # 删除key为gender的键值对
print(r.keys())  # 查询所有的Key

集群操作,以及增删改查

class ConnectDatabaseRedis(object):
    """
    read dict from redis
    """
    def __init__(self, select_env='qa'):
        self.select_env = select_env  # 'prd'/'pre'/'qa'/'dev
        elif self.select_env == 'dev':
            self.target_db_info = {
                'password': 'xx',
                'host': 'xx',
                'port': xx,
                'db': x,
            }

        # target connect
        if self.select_env == 'prd':
            self.con_target = Redis(
                password=self.target_db_info['password'],
                host=self.target_db_info['host'],
                port=self.target_db_info['port'],
                decode_responses=True)

        else:
            pool = redis.ConnectionPool(
                password=self.target_db_info['password'],
                host=self.target_db_info['host'],
                port=self.target_db_info['port'],
                db=self.target_db_info['db'],
                decode_responses=True
            )
            self.con_target = redis.Redis(connection_pool=pool)

    def hm_set(self, redis_key, h_dict):
        """
        pass
        """
        self.con_target.hset(redis_key, mapping=h_dict)

    def h_get(self, redis_key, h_key):
        """
        pass
        """
        return self.con_target.hget(redis_key, h_key)

    def hm_get(self, redis_key, h_key_list):
        """
        pass
        """
        return self.con_target.hmget(redis_key, h_key_list)

    def hm_del(self, redis_key, h_key):
        """
        pass
        """
        self.con_target.hdel(redis_key, h_key)

    def del_h(self, redis_key):
        """
        pass
        """
        self.con_target.delete(redis_key)

复杂度查询
在这里插入图片描述