mybatis implements L2 cache

Posted by healthbasics on Mon, 27 Dec 2021 13:11:28 +0100

Course objectives

  1. Integrated ehcache

1, Mybatis integrated ehcache

1. Why cache

Pull up program performance

2. What kind of data needs to be cached

Data that is rarely modified or not modified at all

Business scenarios, such as time-consuming statistical analysis sql, telephone bill query sql, etc

3. What is ehcache

Ehcache is the most popular pure Java open source caching framework, with simple configuration, clear structure and powerful functions

Note 1: this chapter introduces 2 Version x, 3 X version and 2 The API versions of X are quite different

4. Features of ehcache

4.1 fast enough

Ehcache has been released for a long time. After years of efforts and countless performance tests, ehcache was finally designed in large, high concurrency systems

4.2 simple enough

The interface provided by developers is very simple and clear. It only takes you a few precious minutes from ehcache construction to application and operation. In fact, many developers do not know they are using ehcache. Ehcache is widely used in other open source projects

4.3 pocket size

For this feature, the official gave a lovely name small foot print. Generally, the release version of Ehcache will not reach 2M, V 2.2 3 is only 668KB.

4.4 light enough

The core program only depends on slf4j this package, not one!

4.5 good expansion

Ehcache provides memory and hard disk storage for big data. The latest version allows multiple instances, high flexibility of saving objects, LRU, LFU and FIFO elimination algorithms, and basic attributes support hot configuration and multiple plug-ins

4.6 listener

It's very useful for the cache manager listener and cache evenlistener to broadcast statistics or data consistency

4.7 distributed cache

Starting from Ehcache 1.2, it supports high-performance distributed cache with flexibility and scalability
 

1. Use of ehcache

① . Import dependent

  ②. Core interface

CacheManager: cache manager

Cache: cache object. Several caches can be placed in the cache manager to store the essence of data. All caches implement the Ehcache interface

Element: the constituent unit of a single piece of cached data

  2. Integrating ehcache in SSM

①. Import dependent

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${spring.version}</version>
</dependency>
 
<!--mybatis And ehcache integration-->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>
 
<!--ehcache rely on-->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.10.0</version>
</dependency>

②. Modify the log configuration because ehcache uses Slf4j as log output

We use slf4j for logging and implement it with log4j. Slf4j is very different from other log libraries.

SLF4J(Simple logging Facade for Java) is not a real logging implementation, but an abstraction layer,

It allows you to use any log class library in the background.
 

<!-- log4j2 Log configuration related dependencies -->
    <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 dependent dependencies -->
    <!-- log to configure: Log4j2 + Slf4j -->
    <!-- slf4j Core package-->
    <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>
 
    <!--core log4j2jar package-->
    <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>
    <!--Used with slf4j Keep bridging-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>${log4j2.version}</version>
    </dependency>
    <!--web The project needs to include log4j-web,wrong web The project does not require-->
    <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-web</artifactId>
      <version>${log4j2.version}</version>
      <scope>runtime</scope>
    </dependency>
 
    <!--Need to use log4j2 of AsyncLogger Need to include disruptor-->
    <dependency>
      <groupId>com.lmax</groupId>
      <artifactId>disruptor</artifactId>
      <version>${log4j2.disruptor.version}</version>
    </dependency>

③. Add an ehcache in the Resource XML configuration file

 

<?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">
    <!--Disk storage:Temporarily unused objects in the cache,Transfer to hard disk,be similar to Windows Virtual memory of the system-->
    <!--path:Specifies the path to store objects on the hard disk-->
    <!--java.io.tmpdir Is the default temporary file path. You can print out the specific file path in the following ways System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="java.io.tmpdir"/>
 
 
    <!--defaultCache: Default management policy-->
    <!--eternal: Set cached elements Whether to never expire. If yes true,The cached data is always valid if false Then according to timeToIdleSeconds,timeToLiveSeconds judge-->
    <!--maxElementsInMemory: Cached in memory element Maximum number of-->
    <!--overflowToDisk: If the data in memory exceeds the memory limit, do you want to cache it to disk-->
    <!--diskPersistent: Whether to persist on disk. Means restart jvm Whether the data is valid after. Default to false-->
    <!--timeToIdleSeconds: Object idle time(Unit: Second),It refers to how long an object will become invalid if it is not accessed. Only right eternal by false The is valid. The default value is 0, which means it can always be accessed-->
    <!--timeToLiveSeconds: Object lifetime(Unit: Second),It refers to the time required for an object from creation to expiration. Only right eternal by false The is valid. The default value is 0, which means it can always be accessed-->
    <!--memoryStoreEvictionPolicy: Three cache emptying strategies-->
    <!--FIFO: first in first out (fifo)-->
    <!--LFU: Less Frequently Used (Minimum use).It means the least used all the time. Cached element has a hit Properties, hit The smallest value will be flushed out of the cache-->
    <!--LRU: Least Recently Used(Least recently used). (ehcache Default value).The cached element has a timestamp. When the cache capacity is full and it needs to make room for caching new elements, the element with the farthest timestamp from the current time in the existing cache element will be cleared out of the cache-->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
 
    <!--name:  Cache The name of the must be unique(ehcache I'll take this cache put to HashMap in)-->
    <!--<cache name="stuCache" eternal="false" maxElementsInMemory="100"-->
    <!--overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"-->
    <!--timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>-->
</ehcache>

④ In ApplicationContext ehcache Adding chache configuration to XML

applicationContext-ehcache.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
 
  <!-- use ehcache cache -->
  <bean id="cacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:ehcache.xml"/>
    <property name="shared" value="true"></property>
  </bean>
  <!-- The default is cacheManager -->
  <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="cacheManagerFactory"/>
  </bean>
</beans>

⑤.applicationContext.xml

    <import resource="classpath:applicationContext-ehcache.xml"></import>

⑥. The second level cache of mybaits is the mapper range level, except in sqlmapconfig XML to set the master switch of L2 cache, and also in the specific mapper Enable L2 cache in XML

(1) enable the L2 cache of mybatis

In ApplicationContext mybatis Add to XML

 <!--set up mybaits Cache support-->
        <property name="configurationProperties">
            <props>
                <!-- Global mapper enable caching *You can set this property-->
                <prop key="cacheEnabled">true</prop>
                <!-- When querying, turn off immediate loading of associated objects to improve performance -->
                <prop key="lazyLoadingEnabled">false</prop>
                <!-- Set the loading mode of associated objects. Here is the on-demand loading field(Loading fields by SQL appoint),All fields of the associated table are not loaded to improve performance -->
                <prop key="aggressiveLazyLoading">true</prop>
            </props>
        </property>

Also the corresponding mapper Configuration and use in XML

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

test

3 Can pass select Tagged useCache Property to turn L2 cache on or off

<select id="selectBooksLike1" resultType="com.zy.model.Book" parameterType="java.lang.String" useCache="false">
  select * from t_mvc_book where bname like #{bname}
</select>
Note that there are three:
mybatis The default L2 cache framework is ehcache(org.mybatis.caches.ehcache.EhcacheCache),Seamless combination
Mybatis Once the cache switch is turned on, you can cache a single record or multiple records, hibernate Cannot cache multiple.
Mapper All methods on the interface additionally provide the property of closing the cache

 

 

 

Topics: Java Redis Cache