精打细算缓存的“信息”到底是什么?

时间:2012-03-27 21:09:40

标签: caching dapper

在Dapper的文档中找到here,它声明:

限制和警告

Dapper缓存有关其运行的每个查询的信息 ,这样可以快速实现对象并快速处理参数。当前实现将此信息缓存在ConcurrentDictionary对象中。“

这究竟是什么意思? 例如:它是缓存返回的数据,还是查询本身,还是两者的位?

它还说“此[缓存]数据永远不会被刷新”。如果您要查询的表的设计模式发生变化,这会如何影响“缓存信息”?

1 个答案:

答案 0 :(得分:9)

据我所知,每个查询都会发出Identity,具体取决于sql查询,其命令类型及其参数。缓存是一个具有并发访问权限的字典。

Dictionary<Identity, CacheInfo> _queryCache

CacheInfo对象包含IDataReaderIDBCommand函数以及一些限制缓存量的控制计数器。

由于没有缓存服务器端(数据库架构等),它实际上没有任何影响。

编辑:这就是Identity类看起来如何用于缓存。

private Identity(string sql, CommandType? commandType, string connectionString, Type type, Type parametersType, Type[] otherTypes, int gridIndex)
        {
            this.sql = sql;
            this.commandType = commandType;
            this.connectionString = connectionString;
            this.type = type;
            this.parametersType = parametersType;
            this.gridIndex = gridIndex;
            unchecked
            {
                hashCode = 17; // we *know* we are using this in a dictionary, so pre-compute this
                hashCode = hashCode * 23 + commandType.GetHashCode();
                hashCode = hashCode * 23 + gridIndex.GetHashCode();
                hashCode = hashCode * 23 + (sql == null ? 0 : sql.GetHashCode());
                hashCode = hashCode * 23 + (type == null ? 0 : type.GetHashCode());
                if (otherTypes != null)
                {
                    foreach (var t in otherTypes)
                    {
                        hashCode = hashCode * 23 + (t == null ? 0 : t.GetHashCode());
                    }
                }
                hashCode = hashCode * 23 + (connectionString == null ? 0 : connectionString.GetHashCode());
                hashCode = hashCode * 23 + (parametersType == null ? 0 : parametersType.GetHashCode());
            }
        }

这是CacheInfo

class CacheInfo

        {
            public Func<IDataReader, object> Deserializer { get; set; }
            public Func<IDataReader, object>[] OtherDeserializers { get; set; }
            public Action<IDbCommand, object> ParamReader { get; set; }
            private int hitCount;
            public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
            public void RecordHit() { Interlocked.Increment(ref hitCount); }
        }

最后是缓存的容器。

static readonly System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo> _queryCache = new System.Collections.Concurrent.ConcurrentDictionary<Identity, CacheInfo>();

看看源代码,它写得很好,易于跟踪/调试。只需将文件拖到项目中即可。