Mybatis整合Ehcache、Redis實現二級緩存

Mybatis整合ehcache作爲緩存

1、爲什麼需要緩存
拉高程序的性能

2、什麼樣的數據需要緩存
很少被修改或根本不改的數據

3、業務場景比如:耗時較高的統計分析sql、電話賬單查詢sql等

4、ehcache是什麼?
Ehcache 是現在最流行的純Java開源緩存框架,配置簡單、結構清晰、功能強大
注1:本章介紹的是2.X版本,3.x的版本和2.x的版本API差異比較大

5、ehcache的特點

1 、夠快 Ehcache的發行有一段時長了,經過幾年的努力和不計其數的性能測試,Ehcache終被設計於large, high
concurrency systems.
2 、夠簡單 開發者提供的接口非常簡單明瞭,從Ehcache的搭建到運用運行僅僅需要的是你寶貴的幾分鐘。其實很多開發者都不知道自己用在用Ehcache,Ehcache被廣泛的運用於其他的開源項目
3 、夠袖珍 關於這點的特性,官方給了一個很可愛的名字small foot print ,一般Ehcache的發佈版本不會到2M,V 2.2.3 才 668KB。
4 、夠輕量 核心程序僅僅依賴slf4j這一個包,沒有之一!
5、 好擴展 Ehcache提供了對大數據的內存和硬盤的存儲,最近版本允許多實例、保存對象高靈活性、提供LRU、LFU、FIFO淘汰算法,基礎屬性支持熱配置、支持的插件多
6 、監聽器 緩存管理器監聽器 (CacheManagerListener)和 緩存監聽器(CacheEvenListener),做一些統計或數據一致性廣播挺好用的
7、 分佈式緩存 從Ehcache 1.2開始,支持高性能的分佈式緩存,兼具靈活性和擴展性

核心接口:
CacheManager:緩存管理器
Cache:緩存對象,緩存管理器內可以放置若干cache,存放數據的實質,所有cache都實現了Ehcache接口
Element:單條緩存數據的組成單位

導入相關依賴

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>

<!--mybatis與ehcache整合-->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>

<!--ehcache依賴-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.0</version>
</dependency>

修改日誌配置,因爲ehcache使用了Slf4j作爲日誌輸出
日誌我們使用slf4j,並用log4j來實現。SLF4J不同於其他日誌類庫,與其它有很大的不同。
SLF4J(Simple logging Facade for Java)不是一個真正的日誌實現,而是一個抽象層( abstraction layer),
它允許你在後臺使用任意一個日誌類庫

<!-- log4j2日誌配置相關依賴 -->
    <log4j2.version>2.9.1</log4j2.version>
    <log4j2.disruptor.version>3.2.0</log4j2.disruptor.version>
    <slf4j.version>1.7.13</slf4j.version>

<!-- log4j2日誌相關依賴 -->
    <!-- log配置:Log4j2 + Slf4j -->
    <!-- slf4j核心包-->
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>${slf4j.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--核心log4j2jar包-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-api</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-core</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--用於與slf4j保持橋接-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web工程需要包含log4j-web,非web工程不需要-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>

    <!--需要使用log4j2的AsyncLogger需要包含disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>


在Resource中添加一個ehcache.xml的配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <!--磁盤存儲:將緩存中暫時不使用的對象,轉移到硬盤,類似於Windows系統的虛擬內存-->
    <!--path:指定在硬盤上存儲對象的路徑-->
    <!--java.io.tmpdir 是默認的臨時文件路徑。 可以通過如下方式打印出具體的文件路徑 System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="java.io.tmpdir"/>


    <!--defaultCache:默認的管理策略-->
    <!--eternal:設定緩存的elements是否永遠不過期。如果爲true,則緩存的數據始終有效,如果爲false那麼還要根據timeToIdleSeconds,timeToLiveSeconds判斷-->
    <!--maxElementsInMemory:在內存中緩存的element的最大數目-->
    <!--overflowToDisk:如果內存中數據超過內存限制,是否要緩存到磁盤上-->
    <!--diskPersistent:是否在磁盤上持久化。指重啓jvm後,數據是否有效。默認爲false-->
    <!--timeToIdleSeconds:對象空閒時間(單位:秒),指對象在多長時間沒有被訪問就會失效。只對eternal爲false的有效。默認值0,表示一直可以訪問-->
    <!--timeToLiveSeconds:對象存活時間(單位:秒),指對象從創建到失效所需要的時間。只對eternal爲false的有效。默認值0,表示一直可以訪問-->
    <!--memoryStoreEvictionPolicy:緩存的3 種清空策略-->
    <!--FIFO:first in first out (先進先出)-->
    <!--LFU:Less Frequently Used (最少使用).意思是一直以來最少被使用的。緩存的元素有一個hit 屬性,hit 值最小的將會被清出緩存-->
    <!--LRU:Least Recently Used(最近最少使用). (ehcache 默認值).緩存的元素有一個時間戳,當緩存容量滿了,而又需要騰出地方來緩存新的元素的時候,那麼現有緩存元素中時間戳離當前時間最遠的元素將被清出緩存-->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>


    <!--name: Cache的名稱,必須是唯一的(ehcache會把這個cache放到HashMap裏)-->
    <cache name="stuCache" eternal="false" maxElementsInMemory="100"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

開啓mybatis的二級緩存,applicationContext-mybatis.xml中添加

!--設置mybaits對緩存的支持-->
        <property name="configurationProperties">
            <props>
                <!-- 全局映射器啓用緩存 *主要將此屬性設置完成即可-->
                <prop key="cacheEnabled">true</prop>
                <!-- 查詢時,關閉關聯對象即時加載以提高性能 -->
                <prop key="lazyLoadingEnabled">false</prop>
                <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 -->
                <prop key="aggressiveLazyLoading">true</prop>
            </props>
        </property>

在bookMapper.xml中配置cache

<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

可以通過select標籤的useCache屬性打開或關閉二級緩存

 <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" useCache="true">

測試

@Test
public void cacheMany() {
    Map map = new HashMap();
    map.put("bname", StringUtils.toLikeStr("聖墟"));
    pageBean.setPage(3);
    List<Map> aaaa = this.bookService.listPager(map, pageBean);
    for (Map m : aaaa) {
        System.out.println(m);
    }

    List<Map> aaaa2 = this.bookService.listPager(map, pageBean);
    for (Map m : aaaa2) {
        System.out.println(m);
    }

}

@Test
public void cacheSimgle() {
    Book b1 = this.bookService.selectByPrimaryKey(29);
    System.out.println(b1);
    Book b2 = this.bookService.selectByPrimaryKey(29);
    System.out.println(b2);

}

Mybatis整合redis作爲緩存

redis常用類

  1. Jedis jedis
    就是集成了redis的一些命令操作,封裝了redis的java客戶端
  2. JedisPoolConfig
    Redis連接池
  3. ShardedJedis
    基於一致性哈希算法實現的分佈式Redis集羣客戶端

實現 mybatis 的二級緩存,一般來說有如下兩種方式:

  1. 採用 mybatis 內置的 cache 機制。
  2. 採用三方 cache 框架, 比如ehcache, oscache 等等.

添加redis相關依賴

<!-- redis與spring的整合依賴 -->
    <redis.version>2.9.0</redis.version>
    <redis.spring.version>1.7.1.RELEASE</redis.spring.version>
    
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>${redis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.data</groupId>
      <artifactId>spring-data-redis</artifactId>
      <version>${redis.spring.version}</version>
    </dependency>

** jackson**

<!-- jackson -->
    <jackson.version>2.9.3</jackson.version> 

<!-- jackson -->
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>${jackson.version}</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-annotations</artifactId>
  <version>${jackson.version}</version>
</dependency>

添加兩個redis的配置文件,並將redis.properties和applicationContext-redis.xml配置到applicationContext.xml文件中

redis.properties

redis.hostName=192.168.19.128
redis.port=6379
redis.password=123456
redis.timeout=10000
redis.maxIdle=300
redis.maxTotal=1000
redis.maxWaitMillis=1000
redis.minEvictableIdleTimeMillis=300000
redis.numTestsPerEvictionRun=1024
redis.timeBetweenEvictionRunsMillis=30000
redis.testOnBorrow=true
redis.testWhileIdle=true

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:property-placeholder location="classpath:jdbc.properties,classpath:redis.properties"/>

    <!--整合mybatis框架-->
    <import resource="applicationContext-mybatis.xml"></import>

    <!--整合redis-->
    <import resource="applicationContext-redis.xml"></import>

</beans>

applicationContext-redis.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1. 引入properties配置文件 -->
    <!--<context:property-placeholder location="classpath:redis.properties" />-->

    <!-- 2. redis連接池配置-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!--最大空閒數-->
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <!--連接池的最大數據庫連接數  -->
        <property name="maxTotal" value="${redis.maxTotal}"/>
        <!--最大建立連接等待時間-->
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
        <!--逐出連接的最小空閒時間 默認1800000毫秒(30分鐘)-->
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <!--每次逐出檢查時 逐出的最大數目 如果爲負數就是 : 1/abs(n), 默認3-->
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <!--逐出掃描的時間間隔(毫秒) 如果爲負數,則不運行逐出線程, 默認-1-->
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        <!--是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個-->
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <!--在空閒時檢查有效性, 默認false  -->
        <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
    </bean>

    <!-- 3. redis連接工廠 -->
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          destroy-method="destroy">
        <property name="poolConfig" ref="poolConfig"/>
        <!--IP地址 -->
        <property name="hostName" value="${redis.hostName}"/>
        <!--端口號  -->
        <property name="port" value="${redis.port}"/>
        <!--如果Redis設置有密碼  -->
        <property name="password" value="${redis.password}"/>
        <!--客戶端超時時間單位是毫秒  -->
        <property name="timeout" value="${redis.timeout}"/>
    </bean>

    <!-- 4. redis操作模板,使用該對象可以操作redis  -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="connectionFactory"/>
        <!--如果不配置Serializer,那麼存儲的時候缺省使用String,如果用User類型存儲,那麼會提示錯誤User can't cast to String!!  -->
        <property name="keySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="valueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
        <property name="hashKeySerializer">
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
        </property>
        <property name="hashValueSerializer">
            <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
        </property>
        <!--開啓事務  -->
        <property name="enableTransactionSupport" value="true"/>
    </bean>

    <!-- 5.使用中間類解決RedisCache.RedisTemplate的靜態注入,從而使MyBatis實現第三方緩存 -->
    <bean id="redisCacheTransfer" class="com.Tang.util.RedisCacheTransfer">
        <property name="redisTemplate" ref="redisTemplate"/>
    </bean>
</beans>

將redis緩存引入到mybatis中

1、RedisCache,實現org.apache.ibatis.cache.Cache接口

package com.Tang.util;


import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


public class RedisCache implements Cache //實現類
{
    private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

    private static RedisTemplate<String,Object> redisTemplate;

    private final String id;

    /**
     * The {@code ReadWriteLock}.
     */
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @Override
    public ReadWriteLock getReadWriteLock()
    {
        return this.readWriteLock;
    }

    public static void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisCache.redisTemplate = redisTemplate;
    }

    public RedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.debug("MybatisRedisCache:id=" + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        try{
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>putObject: key="+key+",value="+value);
            if(null!=value)
                redisTemplate.opsForValue().set(key.toString(),value,60, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("redis保存數據異常!");
        }
    }

    @Override
    public Object getObject(Object key) {
        try{
            logger.info(">>>>>>>>>>>>>>>>>>>>>>>>getObject: key="+key);
            if(null!=key)
                return redisTemplate.opsForValue().get(key.toString());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("redis獲取數據異常!");
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        try{
            if(null!=key)
                return redisTemplate.expire(key.toString(),1,TimeUnit.DAYS);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("redis獲取數據異常!");
        }
        return null;
    }

    @Override
    public void clear() {
        Long size=redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                Long size = redisConnection.dbSize();
                //連接清除數據
                redisConnection.flushDb();
                redisConnection.flushAll();
                return size;
            }
        });
        logger.info(">>>>>>>>>>>>>>>>>>>>>>>>clear: 清除了" + size + "個對象");
    }

    @Override
    public int getSize() {
        Long size = redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection)
                    throws DataAccessException {
                return connection.dbSize();
            }
        });
        return size.intValue();
    }
}

2、中間類“RedisCacheTransfer”,解決RedisCache中RedisTemplate的靜態注入

package com.Tang.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

public class RedisCacheTransfer {
    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisCache.setRedisTemplate(redisTemplate);
    }
}

spring與mybatis整合文件中開發二級緩存

<!--設置mybaits對緩存的支持-->
<property name="configurationProperties">
    <props>
        <!-- 全局映射器啓用緩存 *主要將此屬性設置完成即可-->
        <prop key="cacheEnabled">true</prop>
        <!-- 查詢時,關閉關聯對象即時加載以提高性能 -->
        <prop key="lazyLoadingEnabled">false</prop>
        <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的所有字段,以提高性能 -->
        <prop key="aggressiveLazyLoading">true</prop>
    </props>
</property>

在BookMapper.xml中添加自定義cache功能

<cache type="com.Tang.util.RedisCache"></cache>

測試

@Test
public void cacheMany() {
    Map map = new HashMap();
    map.put("bname", StringUtils.toLikeStr("聖墟"));
    pageBean.setPage(3);
    List<Map> aaaa = this.bookService.listPager(map, pageBean);
    for (Map m : aaaa) {
        System.out.println(m);
    }

    List<Map> aaaa2 = this.bookService.listPager(map, pageBean);
    for (Map m : aaaa2) {
        System.out.println(m);
    }

}

@Test
public void cacheSimgle() {
    Book b1 = this.bookService.selectByPrimaryKey(29);
    System.out.println(b1);
    Book b2 = this.bookService.selectByPrimaryKey(29);
    System.out.println(b2);

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章