当前位置:  数据库>mysql

mysql实现本地keyvalue数据库缓存示例

    来源: 互联网  发布时间:2014-10-13

    本文导语:  Key-Value缓存有很多,用的较多的是memcache、redis,他们都是以独立服务的形式运行,在工作中有时需要嵌入一个本地的key-value缓存,当然已经有LevelDb等,但感觉还是太重量级了。 本文实现了一种超级轻量的缓存, 1、实现代码...

Key-Value缓存有很多,用的较多的是memcache、redis,他们都是以独立服务的形式运行,在工作中有时需要嵌入一个本地的key-value缓存,当然已经有LevelDb等,但感觉还是太重量级了。

本文实现了一种超级轻量的缓存,

1、实现代码仅仅需要400行;

2、性能高效,value长度在1K时测试速度在每秒200万左右

3、缓存是映射到文件中的,所以没有malloc、free的开销,以及带来的内存泄露、内存碎片等;

4、如果服务挂掉了,重启后缓存内容继续存在;

5、如果把缓存映射到磁盘文件就算机器挂了,缓存中内容还是会存在,当然有可能会出现数据损坏的情况;

6、一定程度上实现了LRU淘汰算法,实现的LRU不是全局的只是一条链上的,所以只能说在一定程序上实现了;

7、稳定,已经在多个项目中运用,线上部署的机器有几十台,运行了大半年了没出过问题;

8、普通的缓存key、value都是字符串的形式,此缓存的key、value都可以是class、struct对象结构使用更方便;

 老规矩直接上代码:

 

代码如下:

 template
class HashTable
{
public:
    HashTable(const char *tablename, uint32_t tableLen, uint32_t nodeTotal);
    virtual ~HashTable();

    bool Add(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        //check is exist
        uint32_t nodeId = GetIdByKey(key);
        if(nodeId != m_InvalidId) return false;

        nodeId = GetFreeNode();
        if(nodeId == m_InvalidId) return false;

        uint32_t hashCode = key.HashCode();
        Entry *tmpNode = m_EntryAddr + nodeId;
        tmpNode->m_Key = key;
        tmpNode->m_Code = hashCode;
        tmpNode->m_Value = value;

        uint32_t index = hashCode % m_HeadAddr->m_TableLen;
        AddNodeToHead(index, nodeId);

        return true;
    }

    bool Del(K &key)
    {
        AutoLock autoLock(m_MutexLock);

        uint32_t nodeId = GetIdByKey(key);
        if(nodeId == m_InvalidId) return false;

        uint32_t index = key.HashCode() % m_HeadAddr->m_TableLen;

        return RecycleNode(index, nodeId);
    }

    bool Set(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        uint32_t nodeId = GetIdByKey(key);
        if(nodeId == m_InvalidId) return false;

        (m_EntryAddr + nodeId)->m_Value = value;

        return true;
    }

    bool Get(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        uint32_t nodeId = GetIdByKey(key);
        if(nodeId == m_InvalidId) return false;

        value = (m_EntryAddr + nodeId)->m_Value;

        return true;
    }

    bool Exist(K &key)
    {
        AutoLock autoLock(m_MutexLock);

        uint32_t nodeId = GetIdByKey(key);
        if(nodeId == m_InvalidId) return false;

        return true;
    }

    uint32_t Count()
    {
        AutoLock autoLock(m_MutexLock);
        return m_HeadAddr->m_UsedCount;
    }

    //if exist set else add
    bool Replace(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        if(Exist(key)) return Set(key, value);
        else return Add(key, value);
    }

    /***********************************************
    ****LRU: when visit a node, move it to head ****
    ************************************************/
    //if no empty place,recycle tail
    bool LruAdd(K &key, V &value, K &recyKey, V &recyValue, bool &recycled)
    {
        AutoLock autoLock(m_MutexLock);

        if(Exist(key)) return false;

        if(Add(key, value)) return true;

        uint32_t index = key.HashCode() % m_HeadAddr->m_TableLen;
        uint32_t tailId = GetTailNodeId(index);

        if(tailId == m_InvalidId) return false;

        Entry *tmpNode = m_EntryAddr + tailId;
        recyKey   = tmpNode->m_Key;
        recyValue = tmpNode->m_Value;
        recycled  = true;

        RecycleNode(index, tailId);

        return Add(key, value);
    }

    bool LruSet(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        if(Set(key, value)) return MoveToHead(key);
        else return false;
    }

    bool LruGet(K &key, V &value)
    {
        AutoLock autoLock(m_MutexLock);

        if(Get(key, value)) return MoveToHead(key);
        else return false;
    }

    //if exist set else add; if add failed recycle tail than add
    bool LruReplace(K &key, V &value, K &recyKey, V &recyValue, bool &recycled)
    {
        AutoLock autoLock(m_MutexLock);

        recycled = false;

        if(Exist(key)) return LruSet(key, value);
        else return LruAdd(key, value, recyKey, recyValue, recycled);
    }

    void Clear()
    {
        AutoLock autoLock(m_MutexLock);

        m_HeadAddr->m_FreeBase = 0;
        m_HeadAddr->m_RecycleHead = 0;
        m_HeadAddr->m_UsedCount = 0;
        for(uint32_t i = 0; i < m_HeadAddr->m_TableLen; ++i)
        {
            (m_ArrayAddr+i)->m_Head = m_InvalidId;
            (m_ArrayAddr+i)->m_Tail = m_InvalidId;
        }
    }

    int GetRowKeys(vector &keys, uint32_t index)
    {
        AutoLock autoLock(m_MutexLock);

        if(index >= m_HeadAddr->m_TableLen) return -1;

        keys.clear();
        keys.reserve(16);

        int count = 0;
        Array *tmpArray = m_ArrayAddr + index;
        uint32_t nodeId = tmpArray->m_Head;
        while(nodeId != m_InvalidId)
        {
            Entry *tmpNode = m_EntryAddr + nodeId;
            keys.push_back(tmpNode->m_Key);
            nodeId = tmpNode->m_Next;
            ++count;
        }

        return count;
    }

    void *Padding(uint32_t size)
    {
        AutoLock autoLock(m_MutexLock);

        if(size > m_HeadSize - sizeof(TableHead)) return NULL;
        else return m_HeadAddr->m_Padding;
    }

private:
    static const uint32_t m_InvalidId = 0xffffffff;
    static const uint32_t m_HeadSize = 1024;
    struct TableHead
    {
        uint32_t m_TableLen;
        uint32_t m_NodeTotal;
        uint32_t m_FreeBase;
        uint32_t m_RecycleHead;
        uint32_t m_UsedCount;
        char     m_TableName[256];
        uint32_t m_Padding[0];
    };

    struct Array
    {
        uint32_t m_Head;
        uint32_t m_Tail;
    };

    struct Entry
    {
        V m_Value;
        K m_Key;
        uint32_t m_Code;
        uint32_t m_Next;
        uint32_t m_Prev;
    };

    size_t     m_MemSize;
    uint8_t   *m_MemAddr;
    TableHead *m_HeadAddr;
    Array     *m_ArrayAddr;
    Entry     *m_EntryAddr;

    ThreadMutex m_MutexLock;

    bool MoveToHead(K &key);
    uint32_t GetIdByKey(K &key);
    void AddNodeToHead(uint32_t index, uint32_t nodeId);
    bool MoveNodeToHead(uint32_t index, uint32_t nodeId);
    bool RecycleNode(uint32_t index, uint32_t nodeId);
    uint32_t GetTailNodeId(uint32_t index);
    uint32_t GetFreeNode();

    DISABLE_COPY_AND_ASSIGN(HashTable);
};

template
HashTable::HashTable(const char *tablename, uint32_t tableLen, uint32_t nodeTotal)
{
    AbortAssert(tablename != NULL);

    m_MemSize = m_HeadSize + tableLen*sizeof(Array) + nodeTotal*sizeof(Entry);
    m_MemAddr = (uint8_t*)MemFile::Realloc(tablename, m_MemSize);
    AbortAssert(m_MemAddr != NULL);

    m_HeadAddr = (TableHead*)(m_MemAddr);
    m_ArrayAddr = (Array*)(m_MemAddr + m_HeadSize);
    m_EntryAddr = (Entry*)(m_MemAddr + m_HeadSize + tableLen*sizeof(Array));

    m_HeadAddr->m_TableLen = tableLen;
    m_HeadAddr->m_NodeTotal = nodeTotal;
    strncpy(m_HeadAddr->m_TableName, tablename, sizeof(m_HeadAddr->m_TableName));

    if(m_HeadAddr->m_UsedCount == 0)//if first use init array to invalid id
    {
        for(uint32_t i = 0; i < tableLen; ++i)
        {
            (m_ArrayAddr+i)->m_Head = m_InvalidId;
            (m_ArrayAddr+i)->m_Tail = m_InvalidId;
        }

        m_HeadAddr->m_FreeBase = 0;
        m_HeadAddr->m_RecycleHead = 0;
    }
}

template
HashTable::~HashTable()
{
    MemFile::Release(m_MemAddr, m_MemSize);
}

template
bool HashTable::MoveToHead(K &key)
{
    uint32_t nodeId = GetIdByKey(key);
    uint32_t index = key.HashCode() % m_HeadAddr->m_TableLen;

    return MoveNodeToHead(index, nodeId);
}

template
uint32_t HashTable::GetIdByKey(K &key)
{
    uint32_t hashCode = key.HashCode();
    uint32_t index = hashCode % m_HeadAddr->m_TableLen;
    Array *tmpArray = m_ArrayAddr + index;

    uint32_t nodeId = tmpArray->m_Head;
    while(nodeId != m_InvalidId)
    {
        Entry *tmpNode = m_EntryAddr + nodeId;
        if(tmpNode->m_Code == hashCode && key.Equals(tmpNode->m_Key)) break;

        nodeId = tmpNode->m_Next;
    }

    return nodeId;
}

template
void HashTable::AddNodeToHead(uint32_t index, uint32_t nodeId)
{
    if(index >= m_HeadAddr->m_TableLen || nodeId >= m_HeadAddr->m_NodeTotal) return;

    Array *tmpArray = m_ArrayAddr + index;
    Entry *tmpNode = m_EntryAddr + nodeId;
    if(m_InvalidId == tmpArray->m_Head)
    {
        tmpArray->m_Head = nodeId;
        tmpArray->m_Tail = nodeId;
    }
    else
    {
        tmpNode->m_Next = tmpArray->m_Head;
        (m_EntryAddr + tmpArray->m_Head)->m_Prev = nodeId;
        tmpArray->m_Head = nodeId;
    }
}

template
bool HashTable::MoveNodeToHead(uint32_t index, uint32_t nodeId)
{
    if(index >= m_HeadAddr->m_TableLen || nodeId >= m_HeadAddr->m_NodeTotal) return false;

    Array *tmpArray = m_ArrayAddr + index;
    Entry *tmpNode = m_EntryAddr + nodeId;

    //already head
    if(tmpArray->m_Head == nodeId)
    {
        return true;
    }

    uint32_t nodePrev = tmpNode->m_Prev;
    uint32_t nodeNext = tmpNode->m_Next;
    (m_EntryAddr+nodePrev)->m_Next = nodeNext;
    if(nodeNext != m_InvalidId)
    {
        (m_EntryAddr+nodeNext)->m_Prev = nodePrev;
    }
    else
    {
        tmpArray->m_Tail = nodePrev;
    }

    tmpNode->m_Prev = m_InvalidId;
    tmpNode->m_Next = tmpArray->m_Head;
    (m_EntryAddr + tmpArray->m_Head)->m_Prev = nodeId;
    tmpArray->m_Head = nodeId;

    return true;
}

template
bool HashTable::RecycleNode(uint32_t index, uint32_t nodeId)
{
    if(index >= m_HeadAddr->m_TableLen || nodeId >= m_HeadAddr->m_NodeTotal) return false;

    Array *tmpArray = m_ArrayAddr + index;
    Entry *tmpNode = m_EntryAddr + nodeId;

    uint32_t nodePrev = tmpNode->m_Prev;
    uint32_t nodeNext = tmpNode->m_Next;

    if(nodePrev != m_InvalidId)
    {
        (m_EntryAddr + nodePrev)->m_Next = nodeNext;
    }
    else
    {
        tmpArray->m_Head = nodeNext;
    }

    if(nodeNext != m_InvalidId)
    {
        (m_EntryAddr + nodeNext)->m_Prev = nodePrev;
    }
    else
    {
        tmpArray->m_Tail = nodePrev;
    }

    (m_EntryAddr+nodeId)->m_Next = m_HeadAddr->m_RecycleHead;
    m_HeadAddr->m_RecycleHead = nodeId;
    --(m_HeadAddr->m_UsedCount);

    return true;
}

template
uint32_t HashTable::GetTailNodeId(uint32_t index)
{
    if(index >= m_HeadAddr->m_TableLen) return m_InvalidId;

    Array *tmpArray = m_ArrayAddr + index;

    return tmpArray->m_Tail;
}

template
uint32_t HashTable::GetFreeNode()
{
    uint32_t nodeId = m_InvalidId;
    if(m_HeadAddr->m_UsedCount < m_HeadAddr->m_FreeBase)//get from recycle list
    {
        nodeId = m_HeadAddr->m_RecycleHead;
        m_HeadAddr->m_RecycleHead = (m_EntryAddr+nodeId)->m_Next;
        ++(m_HeadAddr->m_UsedCount);
    }
    else if(m_HeadAddr->m_UsedCount < m_HeadAddr->m_NodeTotal)//get from free mem
    {
        nodeId = m_HeadAddr->m_FreeBase;
        ++(m_HeadAddr->m_FreeBase);
        ++(m_HeadAddr->m_UsedCount);
    }
    else
    {
        nodeId = m_InvalidId;
    }

    //init node
    if(nodeId < m_HeadAddr->m_NodeTotal)
    {
        Entry *tmpNode = m_EntryAddr + nodeId;
        memset(tmpNode, 0, sizeof(Entry));

        tmpNode->m_Next = m_InvalidId;
        tmpNode->m_Prev = m_InvalidId;
    }

    return nodeId;
}
 

    
 
 

您可能感兴趣的文章:

  • Thinkphp实现MySQL读写分离操作示例
  • mysql求和函数使用示例
  • C# 中调用 MySQL 存储过程的示例代码
  • mm.mysql那里可以下载?www.mysql.com根本下载不了。谢谢了 iis7站长之家
  • MySQL5创建存储过程的示例
  • PHP获取php,mysql,apche的版本信息示例代码
  • python文件读写并使用mysql批量插入示例分享(python操作mysql)
  • mysql 跨表查询、更新、删除示例
  • mysql 存储过程输入输出参数示例
  • MySQL 自定义函数CREATE FUNCTION示例
  • MySQL存储过程相互调用并获得错误码示例
  • mysql的group_concat函数使用示例
  • aspx中的mysql操作类sqldatasource使用示例分享
  • MYSQL使用inner join 进行 查询/删除/修改示例
  • 数据库查询排序使用随机排序结果示例(Oracle/MySQL/MS SQL Server)
  • php mysql数据库导入脚本(示例)
  • PHP MySQL Select查询示例
  • ASP.NET连接MySql数据库的2个方法及示例
  • mysql存储过程实现split示例
  • python连接mysql调用存储过程示例
  • mysql的SQL_NO_CACHE(在查询时不使用缓存)和sql_cache用法
  • MySQL缓存优化模块 Flashcache
  • 使用Memcache缓存mysql数据库操作的原理和缓存过程浅析
  • mysql 设置查询缓存
  • 清空mysql 查询缓存的可行方法
  • php页面缓存的例子 php缓存降低mysql压力
  • 解析mysql 缓存如何使用内存
  • 浅析MySQL内存的使用说明(全局缓存+线程缓存)
  • mysql的查询缓存说明
  • MySQL DBA教程:Mysql性能优化之缓存参数优化
  •  
    本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
    本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • mysql中如何查看最大连接数(max_connections)和修改最大连接数
  • 在 linux下输入"mysql"命令,进入mysql命令行,但出现“Can't connetc to local MySQL server thuough socket /var/lib/mysql/mysql.sock
  • Mysql查询错误:ERROR:no query specified原因
  • MySQL 重装MySQL后, mysql服务无法启动
  • php安装完成后如何添加mysql扩展
  • 为什么用linux安装盘安装了mysql后,启动mysql,提示找不到mysql.sock文件?
  • mysql中查询当前正在运行的SQL语句并找出mysql中运行慢的sql语句
  • 請教,在redhat linux7.2+mysql 中,系統提示mysql已啟動,網頁卻不能訪問mysql?
  • Myeclipse中自带Tomcat的JDBC连接池配置(mysql和mssql)
  • 求解释: useradd -g mysql mysql -d /home/mysql -s /sbin/nologin
  • MySQL Workbench的下载安装与使用教程
  • 在Linux内安装了Mysql,无法进入Mysql.
  • php中内置的mysql数据库连接驱动mysqlnd简介及mysqlnd的配置安装方式
  • 怎样在linux终端输入mysql直接进入mysql?
  • VS2012+MySQL+SilverLight5的MVVM开发模式介绍
  • c++中关于#include <mysql/mysql.h>的问题?
  • MySQL索引基本知识
  • mysql -u root mysql 怎么解释
  • Mysql设置查询条件(where)查询字段为NULL
  • mm.mysql那里可以下载?www.mysql.com根本下载不了。谢谢了
  • mysql中字符串和时间互相转换的方法(自动转换及DATE_FORMAT函数)
  • MySQL集群 MySQL Cluster


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3