`
Donald_Draper
  • 浏览: 958569 次
社区版块
存档分类
最新评论

Mybatis缓存实现

阅读更多
SqlSessionFactory初始化:http://donald-draper.iteye.com/admin/blogs/2331917
Mybatis加载解析Mapper(xml)文件第一讲:http://donald-draper.iteye.com/blog/2333125
Mybatis加载解析Mapper(xml)文件第二讲:http://donald-draper.iteye.com/blog/2333191
Mybatis 解析Mapper(class):http://donald-draper.iteye.com/blog/2333293
Mybatis的Environment解析详解:http://donald-draper.iteye.com/admin/blogs/2334133
mybatis 动态标签语句的解析(BoundSql):http://donald-draper.iteye.com/admin/blogs/2334135
在前面将Mybatis解析文件,SQLsession更新,查询,常提到Cache,今天我们来看一下
package org.apache.ibatis.cache;
import java.util.concurrent.locks.ReadWriteLock;
public interface Cache
{
    public abstract String getId();
    public abstract int getSize();
    public abstract void putObject(Object obj, Object obj1);
    public abstract Object getObject(Object obj);
    public abstract Object removeObject(Object obj);
    public abstract void clear();
    public abstract ReadWriteLock getReadWriteLock();
}

从Cache接口,可以看出Cache,有id,size,ReadWriteLock属性,put,get,remove Obejct操作;
再来看一下Mybatis默认的缓存PerpetualCache
public class PerpetualCache
    implements Cache
{
    private String id;
    private Map cache;
    private ReadWriteLock readWriteLock;
    public PerpetualCache(String id)
    {
        cache = new HashMap();
        readWriteLock = new ReentrantReadWriteLock();
        this.id = id;
    }
    public String getId()
    {
        return id;
    }
    public int getSize()
    {
        return cache.size();
    }
    public void putObject(Object key, Object value)
    {
        cache.put(key, value);
    }
    public Object getObject(Object key)
    {
        return cache.get(key);
    }
    public Object removeObject(Object key)
    {
        return cache.remove(key);
    }
    public void clear()
    {
        cache.clear();
    }
    public ReadWriteLock getReadWriteLock()
    {
        return readWriteLock;
    }
    public boolean equals(Object o)
    {
        if(getId() == null)
            throw new CacheException("Cache instances require an ID.");
        if(this == o)
            return true;
        if(!(o instanceof Cache))
        {
            return false;
        } else
        {
            Cache otherCache = (Cache)o;
            return getId().equals(otherCache.getId());
        }
    }
    public int hashCode()
    {
        if(getId() == null)
            throw new CacheException("Cache instances require an ID.");
        else
            return getId().hashCode();
    }
}

从PerpetualCache,我们可以看到,PerpetualCache的实现其实是通过Map,put,get,remove,clear操作复用Map相应操作。
再看LruCache
public class LruCache
    implements Cache
{
    private final Cache _flddelegate;//缓存代理
    private Map keyMap;//key Map
    private Object eldestKey;//最老的key
    public LruCache(Cache delegate)
    {
        _flddelegate = delegate;
        setSize(1024);
    }
    public String getId()
    {
        return _flddelegate.getId();
    }
    public int getSize()
    {
        return _flddelegate.getSize();
    }
    //设置缓存大小
    public void setSize(final int size)
    {
        //获取线程线程安全的LinkedHashMap集合
        keyMap = Collections.synchronizedMap(new LinkedHashMap(0.75F, true, size) {
            //同时重写removeEldestEntry,当这个方法返回为true是,则移除eldest
            protected boolean removeEldestEntry(java.util.Map.Entry eldest)
            {
                boolean tooBig = size() > size;
                if(tooBig)
		    //如果Map目前的size大于初始化Map大小,则将最老key赋给eldestKey
                    eldestKey = eldest.getKey();
                return tooBig;
            }

            private static final long serialVersionUID = 4267176411845948333L;
            final int val$size;
            final LruCache this$0;

            
            {
                this$0 = LruCache.this;
                size = i;
                super(x0, x1, x2);
            }
        });
    }
    //将KV对放入缓存
    public void putObject(Object key, Object value)
    {
        _flddelegate.putObject(key, value);
	//并将key放入LRUCache的Key Map中
        cycleKeyList(key);
    }
    public Object getObject(Object key)
    {
        keyMap.get(key);
        return _flddelegate.getObject(key);
    }
    public Object removeObject(Object key)
    {
        return _flddelegate.removeObject(key);
    }
    public void clear()
    {
        _flddelegate.clear();
	//在清除缓存的时候同时,清除Key Map
        keyMap.clear();
    }
    public ReadWriteLock getReadWriteLock()
    {
        return _flddelegate.getReadWriteLock();
    }
    //如果Key Map,已达到负载上限,则从缓存中移除eldestKey
    private void cycleKeyList(Object key)
    {
        keyMap.put(key, key);
        if(eldestKey != null)
        {
            _flddelegate.removeObject(eldestKey);
            eldestKey = null;
        }
    }
}

总结:
Mybatis缓存的实现是通过Map来实现,缓存的新增,获取,移除对象,都是通过Map的相关操作;在LRUCache中,内部有一个缓存代理,LRU的新增,获取,移除对象,是通过缓存代理相关的操作,LRU中还有两个元素,为keyMap和eldestKey,keyMap为缓存中对应的key,keyMap
线程安全的LinkedHashMap,同时,重写了LinkedHashMap的removeEldestEntry,removeEldestEntry方法的含义是,当项Map中添加对象时,是否会需要移除eldest java.util.Map.Entry 对象,KeyMap添加对象后,size大于初始化容量,则从KeyMap中移除对应的key,同时将key赋值于eldestKey,当我们向LRUCache中添加对象时,同时将key添加KeyMap,并处罚是否超出容量检查,如果超出,则从代理缓存中移除对应的对象。

//LinkedHashMap
/**
     * Returns <tt>true</tt> if this map should remove its eldest entry.
     * This method is invoked by <tt>put</tt> and <tt>putAll</tt> after
     * inserting a new entry into the map.  It provides the implementor
     * with the opportunity to remove the eldest entry each time a new one
     * is added.  This is useful if the map represents a cache: it allows
     * the map to reduce memory consumption by deleting stale entries.
     *
     * <p>Sample use: this override will allow the map to grow up to 100
     * entries and then delete the eldest entry each time a new entry is
     * added, maintaining a steady state of 100 entries.
     * <pre>
     *     private static final int MAX_ENTRIES = 100;
     *
     *     protected boolean removeEldestEntry(Map.Entry eldest) {
     *        return size() > MAX_ENTRIES;
     *     }
     * </pre>
     *
     * <p>This method typically does not modify the map in any way,
     * instead allowing the map to modify itself as directed by its
     * return value.  It <i>is</i> permitted for this method to modify
     * the map directly, but if it does so, it <i>must</i> return
     * <tt>false</tt> (indicating that the map should not attempt any
     * further modification).  The effects of returning <tt>true</tt>
     * after modifying the map from within this method are unspecified.
     *
     * <p>This implementation merely returns <tt>false</tt> (so that this
     * map acts like a normal map - the eldest element is never removed).
     *
     * @param    eldest The least recently inserted entry in the map, or if
     *           this is an access-ordered map, the least recently accessed
     *           entry.  This is the entry that will be removed it this
     *           method returns <tt>true</tt>.  If the map was empty prior
     *           to the <tt>put</tt> or <tt>putAll</tt> invocation resulting
     *           in this invocation, this will be the entry that was just
     *           inserted; in other words, if the map contains a single
     *           entry, the eldest entry is also the newest.
     * @return   <tt>true</tt> if the eldest entry should be removed
     *           from the map; <tt>false</tt> if it should be retained.
     */
    protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
        return false;
    }

//Collections
/**
     * Returns a synchronized (thread-safe) map backed by the specified
     * map.  In order to guarantee serial access, it is critical that
     * [b]all[/b] access to the backing map is accomplished
     * through the returned map.<p>
     *
     * It is imperative that the user manually synchronize on the returned
     * map when iterating over any of its collection views:
     * <pre>
     *  Map m = Collections.synchronizedMap(new HashMap());
     *      ...
     *  Set s = m.keySet();  // Needn't be in synchronized block
     *      ...
     *  synchronized (m) {  // Synchronizing on m, not s!
     *      Iterator i = s.iterator(); // Must be in synchronized block
     *      while (i.hasNext())
     *          foo(i.next());
     *  }
     * </pre>
     * Failure to follow this advice may result in non-deterministic behavior.
     *
     * <p>The returned map will be serializable if the specified map is
     * serializable.
     *
     * @param  m the map to be "wrapped" in a synchronized map.
     * @return a synchronized view of the specified map.
     */
    public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) {
        return new SynchronizedMap<>(m);
    }
0
0
分享到:
评论

相关推荐

    MyBatis缓存实现原理及代码实例解析

    主要介绍了MyBatis缓存实现原理及代码实例解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Mybatis缓存机制案例

    通过log4j打印来查看mybatis缓存实现的机制, 原博客http://blog.csdn.net/zouxucong/article/details/68947052

    mybatis+redis缓存配置

    springmvc整合Mybatis,Redis;实现将查询的数据进行二级缓存处理

    springMybatis+redis三级缓存框架

    mybatis二级缓存 + reads做第三级缓存

    Mybatis缓存测试示例

    介绍:一个很简单的Maven项目,对Mybatis的缓存进行测试

    MyBatis-05 缓存机制

    学习MyBatis框架的一级缓存和二级缓存,明确缓存的工作机制,并实现MyBatis框架与第三方缓存EhCache的整合。

    MyBatis 二级缓存 关联刷新实现

    MyBatis 二级缓存 关联刷新实现1、MyBatis缓存介绍2、二级缓存问题2.1、数据不一致问题验证2.2、问题处理思路3、关联缓存刷新实现 1、MyBatis缓存介绍  Mybatis提供对缓存的支持,但是在没有配置的默认情况下,它只...

    Mybatis-plus基于redis实现二级缓存过程解析

    主要介绍了Mybatis-plus基于redis实现二级缓存过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    SpringBoot下Mybatis的缓存的实现步骤

    主要介绍了SpringBoot下Mybatis的缓存的实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

    spring+mybatis+redis缓存入门

    spring+mybatis+redis,mybatis作为缓存,仅仅是入门的配置,我找了好多的教程才最终配置好,资源绝对没问题。请放心下载

    spring-boot-redis-cache-01.rar

    redis集成 mybatis缓存实现和redis session共享问题,详细代码。 结合项目中优点: (1) 因为数据存在内存中,类似于 HashMap ,HashMap 的优势就是查找和操作的时间复杂度都是O (1) 。 (2) Redis 本质上是一个 Key-...

    Mybatis延迟加载和缓存

    Mybatis延迟加载和缓存

    mybatis+redis实现二级缓存

    本项目是基于maven.且需要本地安装了redis之后才能使用,因为项目里面不仅集成了redis,而且里面还集成了shiro。这是从我自己的eclipse中直接copy出来的。实测可用

    springboot+mybatis+ehcache实现缓存数据

    ehcache是一个快速内存缓存框架,java项目里用起来很方便,本来想实现分布式缓存的,但是实践下来redis更适合分布式,所以这里面把分布缓存的配置注释掉了

    Mybatis整合第三方缓存ehcache.docx

    解读: 1、客户从数据库获取数据视...5、由于mybatis的缓存只用了map实现,所以mybatis允许缓存由第三方缓存来实现,并定义了cache接口,第三方只要实现该接口即可,和mybatis整合在一起后由mybatis在程序中进行调用;

    mybatis3.28教程

    mybatis教程分为10部分: 1.mybatis快速入门 2.mybatis CRUD 3.mybatis注解实现 4.mybatis相关优化 5.mybatis解决字段名与实体类属性名不相同的冲突 ...9.mybatis缓存(一级缓存、二级缓存) 10.spring集成mybatis

    spring+springmvc+mybatis项目案例实现用户角色权限管理

    整合EhCache,对Mybatis的二级缓存进行管理和对spring进行缓存管理 整合FastJson对指定http类型的数据进行转换 整合hibernate.validator校验器对controller接口参数进行校验 使用了springmvc统一异常处理 使用了...

    36道面试常问的MyBatis面试题!.docx

    答:MyBatis的缓存分为一级缓存和二级缓存,一级缓存放在session里面,默认就有,二级缓存放在它的命名空间里,默认是不打开的,使用二级缓存属性类需要实现Serializable序列化接口(可用来保存对象的状态),可在它的映射...

    apache ignite实现mybatis二级缓存所需要的jar包

    该资源为apache ignite实现mybatis二级缓存所需要的jar包,需要的可以下载。

    springboot+mybatis+druid+redis实现数据库读写分离和缓存

    springboot+mybatis+druid+redis实现数据库读写分离和缓存

Global site tag (gtag.js) - Google Analytics