当前位置:网站首页>Hibernate L2 cache

Hibernate L2 cache

2022-06-11 08:38:00 Xiao Yi is not bald

One 、 Recognize cache

1. Why cache is needed

Improve program performance

 2. The difference between relational database and non relational database

Relational database

meaning : There is a relationship between data ( contact ) The database of    mysql/Oracle/sqlserver

  Non relational database

meaning : There is no relationship between data ------ In the form of key value pairs

1. Database based on file storage :ehcache

2. Memory based database :redis,memcache

3. Database based on document storage :mongodb

3. What kind of data needs to be cached

Data that is rarely or never modified -------- The data dictionary

4.ehcache What is it?

Ehcache Is now the most popular pure Java Open source caching framework , Simple configuration , The structure is clear , Powerful

notes : This chapter introduces 2.X edition ,3.X Version and 2.X Version of API There is a big difference

5.ehcache Characteristics

1. Fast enough
      Ehcache It's been a long time since the release of , After years of effort and countless performance tests ,Ehcache It was designed in large, high concurrency systems.


2. Simple enough
      The interface provided by the developer is very simple , from Ehcache It only takes you a few precious minutes to build and run . In fact, many developers don't know how to use it Ehcache,Ehcache It is widely used in other open source projects


3. Small enough
      About the nature of this , The official gave a lovely name small foot print , commonly Ehcache The release version of will not reach 2M,V 2.2.3 only 668KB.


4. It's light enough
      The core program only depends on slf4j This bag , Not one of them. !


5. Good expansion
      Ehcache It provides memory and hard disk storage for big data , Recent versions allow multiple instances 、 Preserve the high flexibility of the object 、 Provide LRU、LFU、FIFO Elimination algorithm , Basic properties support hot configuration 、 Many plug-ins are supported


6. Monitor
      Cache manager listener (CacheManagerListener) and Cache listener (CacheEvenListener), It's good to do some statistics or data consistency broadcasting


7. Distributed cache
      from Ehcache 1.2 Start , Support high-performance distributed cache , Both flexibility and scalability

6.ehcache Use

1. Import correlation dependency
      <dependency>
          <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>2.10.0</version>
      </dependency>

  
2. The core interface

      CacheManager: Cache manager


      Cache: Cache object , A number of... Can be placed in the cache manager cache, The quality of stored data cache implement         了 Ehcache Interface


      Element: The unit that makes up a single piece of cached data

3. src:ehcache.xml
 

7.hibernate cache

1.  First level cache
      session

2. Second level cache
      SessionFactory
      Pluggable

8.hibernate(5.2.12.Final) Using the L2 cache step in (ehcache)

1. Import ehcache Related dependencies
      <dependency>
         <groupId>org.hibernate</groupId>
         <artifactId>hibernate-ehcache</artifactId>
        <version>5.2.12.Final</version>
      </dependency>

2. src add to ehcache.xml


3. hibernate.cfg.xml Add L2 cache related configuration in
      <!-- Enable L2 cache -->
      <property name="hibernate.cache.use_second_level_cache">true</property>
      <!-- Turn on query cache -->
      <property name="hibernate.cache.use_query_cache">true</property>
      <!-- EhCache drive -->
      <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>


4. Specify the entity class to enable L2 cache
      <!-- Annotated development -->
      <class-cache usage="read-write" class="entity.Dict"/>

      <!-- xml Configuration mode -->
      <class table="t_sys_dict" name="entity.Dict">
        <cache usage="read-write"/> 
                .......
      </class>


      notes 1: Check all that need to write code to open the L2 cache
     query.setCacheRegion("entity.Dict");// Specify cache policy , The name must be the full class name of the entity class
     query.setCacheable(true);// Manually open L2 cache

 

Two 、 The data dictionary

1. The meaning of the data dictionary

All basic data in a project , All drop-down boxes in the project

Problem solved : Avoid the situation that many tables are built at any time

Table design :

        Data source table : Data source identification , Data source description

        Data item table : Data source identification , Data item key , Data values

3、 ... and 、ehcache Access data

First, import the required classes into the project

utilize map Collection simple implementation cache principle

notes : The comments in the code should be read  

package com.xhy.four.test;
 
import java.util.HashMap;
import java.util.Map;
 
/**
 *  utilize map Collection simple implementation cache principle 
 * 
 *  How to use cache 
 *  Be careful : Just use the cache , There is data in the default cache 
 * 1. Get the corresponding data from the cache first 
 * 2. If you get , Then go straight back 
 * 3. No access to , Then query the database , Put the data corresponding to the database into the cache , Back again 
 * @author Administrator
 *
 */
public class EhcacheDemo1 {
	static Map<String, Object> cache = new HashMap<String, Object>();
	static Object getValue(String key) {
		Object value = cache.get(key);
		if(value == null) {
			System.out.println("hello zs");// Reading data from a database 
			cache.put(key, new String[] {"zs"});
			return cache.get(key);
		}
		return value;
	}
	
	public static void main(String[] args) {
		System.out.println(getValue("sname"));
		System.out.println(getValue("sname"));
	}
}

  Execute query statement

analysis :

The last two garbled codes are set

The output of the first output statement is hello zs/[zs]

reason : The entry method will start from ehcache Middle value , can ehcache There is no value in the database, so go to the database to read the data

if Judge the output inside hello zs , Then the return value returns zs

The result of the second output statement is [zs]

reason : Because it's already worth it , So go straight back

Demonstrate using cache to store data

 

Import the required xml file

 

The xml file ( Comments are very important )  

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">
    <!-- Disk storage : Will cache objects that are temporarily not used , Transfer to hard disk , Be similar to Windows Virtual memory of the system -->
    <!--path: Specifies the path where objects are stored on the hard disk -->
    <!--java.io.tmpdir  Is the default temporary file path .  The specific file path can be printed as follows  System.out.println(System.getProperty("java.io.tmpdir"));-->
    <diskStore path="D://xxx"/>
 
 
    <!--defaultCache: Default management strategy -->
    <!--eternal: Set cached elements Whether it will never expire . If true, The cached data is always valid , If false Then according to timeToIdleSeconds,timeToLiveSeconds Judge -->
    <!--maxElementsInMemory: Cached in memory element The maximum number of -->
    <!--overflowToDisk: If the data in memory exceeds the memory limit , Do you want to cache to disk -->
    <!--diskPersistent: Whether to persist on disk . Restart jvm after , Is the data valid . The default is false-->
    <!--timeToIdleSeconds: Object free time ( Company : second ), It refers to how long an object will be invalid if it is not accessed . Only right eternal by false Effective . The default value is 0, Indicates that you can always access -->
    <!--timeToLiveSeconds: Object lifetime ( Company : second ), It refers to the time required for an object from creation to expiration . Only right eternal by false Effective . The default value is 0, Indicates that you can always access -->
    <!--memoryStoreEvictionPolicy: The cache 3  Kind of emptying strategy -->
    <!--FIFO:first in first out ( fifo )-->
    <!--LFU:Less Frequently Used ( Use at least ). It means the least used . The cached element has a hit  attribute ,hit  The smallest value will be flushed out of the cache -->
    <!--LRU:Least Recently Used( Recently at least use ). (ehcache  The default value is ). Cached elements have a timestamp , When the cache capacity is full , And when you need to make room to cache new elements , The element whose timestamp is farthest from the current time among the existing cache elements will be flushed out of the cache -->
    <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
                  timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
 
 
    <!--name: Cache The name of , Must be unique (ehcache Will take this. cache Put it in HashMap in )-->
    <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
           overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
           timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
</ehcache>

Start demonstrating

package com.xhy.four.test;
 
import com.xhy.four.util.EhcacheUtil;
 
/**
 *  Demonstrate using cache to store data 
 * @author Administrator
 *
 */
public class EhcacheDemo2 {
	public static void main(String[] args) {
		System.out.println(System.getProperty("java.io.tmpdir"));
		EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
		System.out.println(EhcacheUtil.get("com.javaxl.four.entity.Book", 11));
	}
}

If the top ehcache.xml In the document

If not , The data will be stored in by default java.io.tmpdir Go inside

Let's run the method

analysis : First, call the stored method in the tool class

 public static void put(String cacheName, Object key, Object value) {
        Cache cache = cacheManager.getCache(cacheName);
        if (null == cache) {
            // Add a file named... In the default configuration cacheName Of Cache
            cacheManager.addCache(cacheName);
            cache = cacheManager.getCache(cacheName);
        }
        cache.put(new Element(key, value));
    }

Because now there is no slot , So in if Judge , Added a slot , Then it calls the fetching method in the tool class

 public static Object get(String cacheName, Object key) {
        Cache cache = cacheManager.getCache(cacheName);
        Element element = cache.get(key);
        return null == element ? null : element.getValue();
    }

The results are as follows :

How to make me in ehcache.xml File generated in the folder of the path in

take ehcache.xml Medium cache Change the label to look like the following  

  take EhcacheDemo2 The file name in has also been changed

  And then run :

 

  The data is stored in a folder  

Four 、hibernate Use echcache As a second level cache

 

package com.xhy.four.test;
 
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
 
import com.xhy.four.dao.UserDao;
import com.xhy.entity.User;
import com.xhy.two.util.SessionFactoryUtil;
 
 
/**
 *  Demonstrate that a single user has used the cache 
 * @author Administrator
 *
 */
public class EhcacheDemo3 {
	/**
	 *  By default ,sql The statement is formed three times , To improve performance , Must use L2 cache SessionFactory cache 
	 *  <!--  Enable L2 cache  -->
	 *  <property name="hibernate.cache.use_second_level_cache">true</property>
      <!--  Turn on query cache  -->
      <property name="hibernate.cache.use_query_cache">true</property>
      <!-- EhCache drive  -->
      	 Be careful : Here you must use hibernate Of 5.2.12.Final  edition 
      <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>
      
      	 Add labels to the mapping file 
      	<cache usage="read-write" region="com.zking.one.entity.User"/>
      	 there region refer to Ehcache.xml in cacheName
	 * @param args
	 */
	@Test
	public void test2() {
		UserDao userDao  = new UserDao();
		User u = new User();
		u.setId(7);
		User user = userDao.get(u);
		System.out.println(user);
		User user2 = userDao.get(u);
		System.out.println(user2);
		User user3 = userDao.get(u);
		System.out.println(user3);
		
	}
	
	/**
	 *  The same session,sql Statement is generated only once , First level cache is used here 
	 */
	@Test
	public void test1() {
		Session session = SessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		User user = session.get(User.class, 7);
		System.out.println(user);
		User user2 = session.get(User.class, 7);
		System.out.println(user2);
		User user3 = session.get(User.class, 7);
		System.out.println(user3);
		
		transaction.commit();
		session.close();
	}
}

function test1 Result display :

 

analysis :

here sql Statement occurs only once , Because the L1 cache is used by default , Because of the use of session Is the same session

function test2 Result display :

analysis : here sql The statement is run three times because , Every time you run it, you are new One of the userdao, Every time a new session 

  Solution : Use sessionFactory Level cache

First step : Enable L2 cache ( Write the following code to hibernate.cfg.xml in )

<!--  Enable L2 cache  -->
		<property name="hibernate.cache.use_second_level_cache">true</property>
		<!--  Turn on query cache  -->
		<property name="hibernate.cache.use_query_cache">true</property>
		<!-- EhCache drive  -->
		<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property>

The second step : Change the configuration in the configuration of what to put in the L2 cache

<cache usage="read-write" region="com.xhy.entity.User"/>

The results are as follows :

You can see test2 There is only one after running sql Statement  

5、 ... and 、hibernate Multiple records cache  

package com.sg.four.test;
 
import java.util.List;
 
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
 
import com.sg.two.util.SessionFactoryUtil;
 
 
/**
 * hibernate L2 cache will not cache multiple pieces of data at the same time 
 * @author Administrator
 *
 */
public class EhcacheDemo4 {
	public static void main(String[] args) {
		Session session = SessionFactoryUtil.getSession();
		Transaction transaction = session.beginTransaction();
		
		Query query = session.createQuery("from User");
		query.setCacheable(true);
		List list = query.list();
		System.out.println(list);
		List list2 = query.list();
		System.out.println(list2);
		List list3 = query.list();
		System.out.println(list3);
		
		
		transaction.commit();
		session.close();
	}
}

Mainly used :query.setCacheable(true); This code , This is the switch to enable simultaneous caching of multiple data

Result display :

Comment to query.setCacheable(true); Running results :

 

  There are three in all sql sentence

open query.setCacheable(true); after :

 

  There is only one sql 

原网站

版权声明
本文为[Xiao Yi is not bald]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020508246487.html