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

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的插件体系,可以通过配置启用并指定实现类,如 EhCache 或 Redis。 启用二级缓存需要在MyBatis的配置文件中开启缓存支持,并在对应的Mapper接口或XML配置中声明启用二级缓存。每个Mapper...

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

    4. 开启二级缓存需要在全局配置中设置`cacheEnabled`为true,并在mapper.xml中添加`&lt;cache&gt;`标签,同时实体类需实现序列化接口。 MyBatis还有一些与缓存相关的配置属性: - `cacheEnabled`:全局控制二级缓存的开关...

    Mybatis缓存机制案例

    Mybatis缓存机制是数据库操作中的重要组成部分,它能够提高数据访问效率,减少对数据库的重复查询。在Mybatis中,缓存分为一级缓存和二级缓存,这两种缓存各有其特点和应用场景。 一级缓存是SqlSession级别的缓存,...

    Mybatis缓存测试示例

    二级缓存使用的是 Ehcache 或其他缓存实现,可以跨多个SqlSession共享数据。但需要注意的是,二级缓存对并发控制要求较高,因此在高并发环境下需要谨慎使用,以防止数据不一致问题。 在进行Mybatis缓存测试时,我们...

    mybatis+redis缓存配置

    #### 一、MyBatis缓存机制概述 在MyBatis中,缓存是一项重要的性能优化措施。它能够显著减少数据库的访问次数,提高应用程序的响应速度。MyBatis提供了两种级别的缓存支持:一级缓存和二级缓存。 - **一级缓存**:...

    Mybatis缓存开源架构源码2021.pdf

    它基于 Ehcache 或其他可配置的缓存实现,需要在 MyBatis 配置文件中开启,并且对应的 Mapper XML 文件也需要启用二级缓存注解。二级缓存允许在不同 SqlSession 中缓存相同查询的结果,提高了数据访问效率。但是,...

    Mybatis系列教程Mybatis缓存共17页.pdf

    二级缓存由Mybatis全局配置文件中的元素开启,并通过实现Cache接口来自定义缓存实现。二级缓存可以被多个SqlSession共享,提高了数据读取的效率。然而,需要注意的是,二级缓存可能会引发并发问题,因此在高并发环境...

    springMybatis+redis三级缓存框架

    在实现二级缓存时,我们可以选择EhCache作为缓存实现,EhCache是一款广泛使用的Java缓存库,具有良好的性能和可扩展性。 然而,当系统负载高或者需要跨应用共享缓存时,内存缓存(如EhCache)可能无法满足需求,...

    MyBatis-05 缓存机制

    二级缓存的配置在MyBatis的XML配置文件中进行,需要开启对应的Mapper标签,并指定缓存实现类。二级缓存默认是关闭的,因为它可能会引发并发问题,需要开发者根据实际需求谨慎使用。 EhCache是一款广泛使用的Java...

    深入理解MyBatis中的一级缓存与二级缓存

    开启二级缓存需要在MyBatis的配置文件中加入 `&lt;settings&gt; &lt;setting name="cacheEnabled" value="true"/&gt;&lt;/settings&gt;`,并在需要开启二级缓存的mapper.xml中加入 `&lt;cache/&gt;`标签,同时让使用二级缓存的POJO类实现...

    mybatis 缓存的简单配置

    MyBatis的缓存分为一级缓存和二级缓存,它们各自有不同的作用和实现方式。 一级缓存是SqlSession级别的,也称为本地缓存。当我们在一个SqlSession中执行SQL查询后,查询结果会被存储在SqlSession中。如果在同一个...

    缓存处理-mybatis层

    2. 分布式环境下的缓存:在分布式系统中,二级缓存可能导致数据冲突,这时可以考虑使用分布式缓存解决方案,如Redis或Memcached,配合MyBatis的插件实现分布式缓存。 3. 缓存穿透和缓存雪崩:缓存穿透是指查询的...

    基于mybatis自定义缓存配置Redis

    3. **配置MyBatis**:在MyBatis的配置文件(mybatis-config.xml)中,启用二级缓存并指定使用Redis作为缓存实现。添加如下配置: ```xml &lt;plugin interceptor="com.example.mybatis.redis....

    mybatis缓存的配置文件

    5. **自定义缓存实现**:如果你有更复杂的缓存需求,可以实现`org.apache.ibatis.cache.Cache`接口来自定义缓存行为。 通过以上配置,你可以有效地利用MyBatis的缓存机制,提高应用的性能。但是需要注意的是,缓存...

    【MyBatis学习笔记八】——MyBatis缓存.zip

    2. 分布式环境:在分布式环境中,单纯依赖MyBatis的二级缓存可能无法满足需求,此时可以结合Redis、Memcached等分布式缓存工具来实现更高效的缓存策略。 3. 缓存穿透:防止大量不存在的查询请求导致缓存被击穿,可以...

    mybatis-demo13-缓存.zip

    在本示例`mybatis-demo13-缓存.zip`中,我们将探讨如何将Ehcache集成到MyBatis中,以实现高效的缓存管理。 首先,我们需要了解Ehcache的基本概念。Ehcache是一个开放源码的、高性能的分布式缓存系统,支持内存和...

    mybatis+redis实现二级缓存

    3. **配置MyBatis**:在MyBatis的配置文件mybatis-config.xml中,启用二级缓存并指定使用Redis作为缓存实现。还需要为每个需要缓存的Mapper配置对应的缓存实现。 4. **Shiro集成**:Shiro是一个强大的安全管理框架...

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

    Mybatis-plus基于Redis实现二级缓存过程解析 Mybatis-plus是一款基于Java语言的持久层框架,旨在简化数据库交互操作。然而,在高并发、高性能的应用场景中,数据库的查询操作可能会成为性能瓶颈。为了解决这个问题...

    分布式系统架构——使用Redis做MyBatis的二级缓存 - CSDN博客1

    MyBatis的二级缓存机制允许开发者自定义缓存实现,这就为我们使用Redis这样的分布式缓存系统提供了可能。Redis是一个高性能的键值存储系统,适合存储大量的字符串、列表、集合、哈希表等数据结构,并支持丰富的操作...

Global site tag (gtag.js) - Google Analytics