Mybatis整合Redis實現二級緩存

Mybatis集成ehcache

1. 爲何須要緩存java

   拉高程序的性能web

2. 什麼樣的數據須要緩存redis

   不多被修改或根本不改的數據算法

   業務場景好比:耗時較高的統計分析sql、電話帳單查詢sqlspring

3. ehcache是什麼sql

   Ehcache 是如今最流行的純Java開源緩存框架,配置簡單、結構清晰、功能強大apache

   1:本章介紹的是2.X版本,3.x的版本和2.x的版本API差別比較大api

 4. ehcache的特色緩存

  4.1 夠快mybatis

      Ehcache的發行有一段時長了,通過幾年的努力和不可勝數的性能測試,Ehcache終被設計於large, high concurrency systems.

  4.2 夠簡單

      開發者提供的接口很是簡單明瞭,從Ehcache的搭建到運用運行僅僅須要的是你寶貴的幾分鐘。其實不少開發者都不知道本身用在用EhcacheEhcache被普遍的運用於其餘的開源項目

  4.3 夠袖珍

      關於這點的特性,官方給了一個很可愛的名字small foot print ,通常Ehcache的發佈版本不會到2MV 2.2.3 668KB

  4.4 夠輕量

      核心程序僅僅依賴slf4j這一個包,沒有之一!

  4.5 好擴展

      Ehcache提供了對大數據的內存和硬盤的存儲,最近版本容許多實例、保存對象高靈活性、提供LRULFUFIFO淘汰算法,基礎屬性支持熱配置、支持的插件多

  4.6 監聽器

      緩存管理器監聽器 CacheManagerListener)和 緩存監聽器(CacheEvenListener,作一些統計或數據一致性廣播挺好用的

  4.7 分佈式緩存

      Ehcache 1.2開始,支持高性能的分佈式緩存,兼具靈活性和擴展性

 

3. ehcache的使用

  3.1 導入相關依賴

 

  3.2 核心接口

      CacheManager:緩存管理器

      Cache:緩存對象,緩存管理器內能夠放置若干cache,存放數據的實質,全部cache都實現了Ehcache接口

      Element:單條緩存數據的組成單位

   4. ssm中整合ehcache

  4.1 導入相關依賴

 

<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>

  

 applicationContext.xml中加入chache配置

 

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

    <!-- 使用ehcache緩存 -->
    <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:ehcache.xml"/>
        <property name="shared" value="true"></property>
    </bean>
    <!-- 默認是cacheManager -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="cacheManagerFactory"/>
    </bean>
</beans>

 

  

 mybaits的二級緩存是mapper範圍級別,除了在SqlMapConfig.xml設置二級緩存的總開關,還要在具體的mapper.xml中開啓二級緩存

  開啓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>

 

  在XxxMapper.xml中配置cache

 

 <!-- 如下兩個<cache>標籤二選一,第一個能夠輸出日誌,第二個不輸出日誌 -->
          <!--<cache type="org.mybatis.caches.ehcache.LoggingEhcache" />-->
          <!--<cache type="org.mybatis.caches.ehcache.EhcacheCache" />-->
          <!--eviction="FIFO"  回收策略爲先進先出-->
          <!--flushInterval="60000" 自動刷新時間60s-->
          <!--size="512" 最多緩存512個引用對象-->
          <!--readOnly="true"  只讀-->
          <cache type="org.mybatis.caches.ehcache.EhcacheCache">
            <property name="timeToIdleSeconds" value="3600"/>
            <property name="timeToLiveSeconds" value="3600"/>
            <property name="maxEntriesLocalHeap" value="1000"/>
            <property name="maxEntriesLocalDisk" value="10000000"/>
            <property name="memoryStoreEvictionPolicy" value="LRU"/>
          </cache>

 能夠經過select標籤的useCache屬性打開或關閉二級緩存

        <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Long" useCache="false"></select>

 

 注意:

一、 mybatis默認使用的二級緩存框架就是ehcacheorg.mybatis.caches.ehcache.EhcacheCache),無縫結合

二、 Mybatis緩存開關一旦開啓,可緩存單條記錄,也可緩存多條,hibernate不能緩存多條。

三、 Mapper接口上的全部方法上另外提供關閉緩存的屬性

使用緩存截圖:

 

 

 

 

 

 

Mybatis集成redis

1. redis經常使用類

  1.1 Jedis

      jedis就是集成了redis的一些命令操做,封裝了redisjava客戶端

  

  1.2 JedisPoolConfig

      Redis鏈接池

 

  1.3 ShardedJedis

      基於一致性哈希算法實現的分佈式Redis集羣客戶端

 

   實現 mybatis 的二級緩存,通常來講有以下兩種方式:

   1) 採用 mybatis 內置的 cache 機制。

   2) 採用三方 cache 框架, 好比ehcache, oscache 等等.

 

2. 添加jar依賴

 

 <!-- 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>

 

  注:

 版本衝突問題:

      1. ClassNotFoundException  redis/client/util/geoUtils    說這個類找不到。

      2. org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisTemplate' defined in class path resource [applicationContext.xml]

         說建立 redisTemplate bean 對象時失敗了。

 

      redis.client 2.9.0 ---- spring-data-redis  1.7.1.RELEASE

      redis.client 2.9.0 ---- spring-data-redis  1.7.2.RELEASE    這兩個是可使用的

log4j2配置

 

  <!--核心log4j2jar包-->
    <!-- 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>

 

  

 

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>

 

  

 

 spring + redis 集成實現緩存功能(mybatis無關)

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

      redis.properties

      applicationContext-redis.xml

注:

  spring中引入第二個屬性文件會出現「找不到某個配置項」錯誤,這是由於spring只容許有一個<context:property-placeholder/>    

 

      <!--引入一個屬性文件的寫法-->      

      <context:property-placeholder ignore-unresolvable="true" location="classpath:jdbc.properties" />

 

      <!--引入兩個或多個屬性文件的寫法-->

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

 

經過import標籤將applicationContext-redis.xml導入到applicationContext.xml文件中

           <!--導入redis配置-->

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

redis.properties

redis.hostName=192.168.136.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"/>
    <import resource="applicationContext-redis.xml"></import>
    <import resource="applicationContext-mybatis.xml"></import>
</beans>

  redis緩存引入到mybatis

 

   建立mybatis的自定義緩存類「RedisCache」,必須實現org.apache.ibatis.cache.Cache接口

 RedisCache.java

package com.lingerqi.util;


import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 org.springframework.stereotype.Component;

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();
    }
}

  靜態注入中間類RedisCacheTransfer」,解決RedisCacheRedisTemplate的靜態注入,從而使MyBatis實現第三方緩存

        RedisCacheTransfer.java

package com.lingerqi.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);
    }
}

springmybatis整合文件中開發二級緩存

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

 

  XxxMapper.xml中添加自定義cache功能

 

<cache type="com.lingerqi.util.RedisCache"
       eviction="LRU"
       flushInterval="6000000"
       size="1024"
       readOnly="false"></cache>

  注意:

Cachevalue進行WeakReference包裝;WeakReference不會強制對象保存在內存中。它擁有比較短暫的生命週期,容許你使用垃圾回收器的能力去權衡一個對象的可達性。在垃圾回收器掃描它所管轄的內存區域過程當中,一旦gc發現對象是weakReference可達,就會把它放到ReferenceQueue中,等下次gc時回收它。

測試結果:

 

 

@Test
    public void selectByPrimaryKeyCacheOne() {
        System.out.println(bookService.selectByPrimaryKey(10006));
        System.out.println(bookService.selectByPrimaryKey(10006));
    }

    @Test
    public void selectByPrimaryKeyCacheMany() {
        Map map = new HashMap();
        map.put("bname","聖墟");

//        pageBean.setPagination(false);
        pageBean.setPage(6);
        List<Map> books = this.bookService.listPager(map, pageBean);
        for (Map b : books) {
            System.out.println(b);
        }

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

 

  

 

 

 

 

 

 

 

 

 

<!--設置mybaits對緩存的支持-->

    <property name="configurationProperties">

        <props>

            <!-- 全局映射器啓用緩存 *主要將此屬性設置完成便可-->

            <prop key="cacheEnabled">true</prop>

            <!-- 查詢時,關閉關聯對象即時加載以提升性能 -->

            <prop key="lazyLoadingEnabled">false</prop>

            <!-- 設置關聯對象加載的形態,此處爲按需加載字段(加載字段由SQL指 定),不會加載關聯表的全部字段,以提升性能 -->

            <prop key="aggressiveLazyLoading">true</prop>

        </props>

    </property>

相關文章
相關標籤/搜索