There are popular products on the homepage of the online mall, so the click rate of these products is very high. When a user clicks on a popular product, he needs to enter the product's detailed information page, just like on Taobao. Then every time you click, you have to go to the background to query the product's detailed information, and you will send the corresponding SQL statement. Every time you refresh the detailed page, you will also send the SQL statement. In this way, the performance will definitely be greatly affected. Then using Hibernate's secondary cache can solve this problem.
Some people may think that we can use redirection. In this way, when the user first visits, they can find out the information and put it in the session. In the future, every time the user refreshes, they can go to the session, so there is no need to query in the database. This makes sense, but it cannot solve the above problem, because what we want to solve is that multiple users will access the same product and click on the same product. Redirection can only ensure that the same user will click or refresh. But the secondary cache can solve these problems.
Let’s first explain the secondary caching technology based on Hibernate4.3 in detail, and then make a specific configuration for this project.
1. Hibernate4.3 Level 2 Cache Basic Configuration
Unlike Hibernate3, the core package of Hibernate4.3 does not have cache-related classes. If we want to use secondary cache, we need to add the cached jar package. From the official download of hibernate-release-4.3.11.Final, there are jar packages required for secondary cache, which must be added to the project first. as follows:
Then we configure the secondary cache-related configuration in hibernate.cfg.xml:
<hibernate-configuration> <session-factory> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="show_sql">true</property> <!-- Configure the secondary cache provider, note that this is not a cached jar package--> <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <mapping /> <mapping /> <mapping /> <!-- Which classes to configure support caching? This mainly displays popular products on the homepage, so Product class supports caching--> <class-cache usage="read-only"/> </session-factory> </hibernate-configuration>
Then we open the tomcat server, then visit the homepage, click on popular products, and no SQL statements are sent in the background. You may wonder, is the second-level cache that is that simple? Just configure these two items? In fact, the reason why the Level 2 cache has taken effect so far is that it has a default configuration. There is an ehcache-failsafe.xml file in the above ehcache-core-2.4.3.jar, which already has a default configuration. We will analyze it in detail later. Let’s first analyze Hibernate’s query strategy:
2. Hibernate4.3 query strategy
Hibernate supports two query methods: session query and hql query.
There are session.save() update() delete() get() load() and other methods in the session. This method only operates on one record, and the default is to support level 2 cache without any configuration. Therefore: the read-only configuration is effective for session. If read-only is configured in the secondary cache in session, the session.update() and delete() operations will both fail. If you want to succeed, you need to configure read-write. But save() and get() load() are successful.
hql: This method is used to operate multiple records by default, such as list() and executeUpdate() methods. This method defaults to the secondary cache configuration including read-only is invalid. hql's list() querys multiple records, directly querys the database, and handes the query results to the secondary cache, which facilitates the call of get() and load(). executeUpdate does not support secondary caching, and it is also directly updated to the database. Hibernate will ensure that the database and cache are synchronized. Note: hql does not have a save() method. If you need to insert data, you can only call the session.save() method.
[Note]: The first-level cache (existed by default) in Hibernate is also called session-level cache, not used to improve performance, but to handle transactions; the second-level cache is a sessionFactory cache, which is valid for all sessions, and its life cycle is the same as the sessionFactory (the sessionFactory is a singleton and will be created when the project starts).
For specific query strategies, let’s look at the following picture:
【Note】: If the text of the picture is too small, you can drag the picture to a new window to view~
The above is the query strategy of Hibernate. Let’s continue to look at the configuration of the secondary cache.
3. Hibernate 4.3 Level 2 Cache Advanced Configuration
As mentioned above, the reason why we can use Level 2 cache after configuring two items in hibernate.cfg.xml is because there is a default configuration. Let’s take a look at this default configuration first:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <!-- If the cache memory overflows, it will be stored to the hard disk space --> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" : <!-- The maximum number of objects supported by memory --> eternal="false" : <!-- Whether the object is permanently valid, it is recommended to be false, so that the following two parameters will be valid --> timeToIdleSeconds="60" : <!-- The interval period of an object, the default unit is seconds. That is, if no one uses this object after 60 seconds, it will be destroyed in advance-> timeToLiveSeconds="120" :<!-- The life cycle of the object is seconds--> overflowToDisk="true" :<!-- Whether overflow to the hard disk is supported, it is recommended to be true --> maxElementsOnDisk="10000000" :<!-- The maximum number of objects supported on the hard disk--> memoryStoreEvictionPolicy="LRU" :<!-- Object replacement policy--> /> </ehcache>
The relevant explanation about the default configuration is already in the comments above. We now know that it is precisely because of this default configuration that the Hibernate 4.3's second-level cache can be executed correctly. Now if we want to configure the cache ourselves, we need to create a new ehcache.xml file in the src directory and then reconfigure the above configuration items. Next, we need to test each configuration. Before testing, I will post the situation displayed on the homepage and make a number. Let's explain it later when testing:
The above is part of the content displayed on the home page. Hibernate has found the display information from the database and it has been displayed. We will number them and it will be easier to analyze when we test the cache later. Let's start testing the cache configuration items above:
Test 1: Test the number of objects in memory. Change the configuration to the following situation:
<defaultCache maxElementsInMemory="6" <!-- Setting only supports 6 caches --> eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="FIFO" :<!-- First-in, First-out--> />
After the configuration is completed, we restart the server and open the home page. Since there are 6 configured, only the last 6 records found in the cache are stored, that is, number 3-8. We click any of the products in 3-8 to enter the product details page. Note that the console in the background does not output any query information, which means that no SQL statement is sent. However, when we click on the product number 2, a SQL statement is sent in the background, that is, the database is queryed. We backed and clicked on the product 2 again, and no SQL statement is sent, which means that it has been put into the cache, but the cache only supports 6 data. Because the configured object replacement strategy is first in, first out, so the number 3 in the cache has just been removed. We clicked 3 to try and sent an SQL statement. So the test is completed, and the second level cache execution is normal.
Test 2: The life cycle of the test object. Change the configuration to the following situation:
<defaultCache maxElementsInMemory="100" eternal="false" <!-- Only by matching false can the following life cycle be set--> timeToIdleSeconds="20" timeToLiveSeconds="40" overflowToDisk="false" memoryStoreEvictionPolicy="FIFO" />
The cache time is configured as 40 seconds, and if there is no operation in 20 seconds, it will be removed. Since we have assigned 100 records, the numbers 1-8 above are all in the cache. After we enable the server, we click on any one, for example, click on number 8, and no SQL statement is issued. Normally, after 20 seconds, click on number 8 and send an SQL statement, indicating that the life cycle we configured has taken effect. Note here that the configuration cannot be too short, such as 10 seconds, because tomcat will take several seconds to start. If there is less configuration, the time may have been up before testing...then it won't work.
Test 3: Test whether the secondary cache supports hard disk storage.
<defaultCache maxElementsInMemory="4" eternal="false" <!-- Only by setting false can the following life cycle be set --> timeToIdleSeconds="100" timeToLiveSeconds="200" overflowToDisk="true" <!-- Only by setting true can the hard disk storage be supported --> memoryStoreEvictionPolicy="FIFO" />
We set the support hard disk storage to true and configure the maximum storage capacity of the secondary cache to 4. Restart the server. Because the secondary cache stores up to 4 records, it must be numbered 5-8. Clicking 5-8 will definitely not send SQL statements, but when we click 1-4, we will not send SQL statements, because we have set up support for hard disk storage, Hibernate will store the query results on the hard disk, so we can also get the data directly without sending SQL statements.
Test 4: Test the replacement strategy of Level 2 cache
<defaultCache <!-- FIFO has been eliminated and will not be used again... LRU: The algorithm that has been accessed at least recently (time policy), will ignore the access frequency, and the one that has been accessed at the farthest time will be replaced by LFU: The algorithm that has been used most recently (frequency measurement), will ignore the order of access, and the one that has the least access frequency will be replaced by --> maxElementsInMemory="3" eternal="false" <!-- Only when it is configured as false can the following life cycle be set --> timeToIdleSeconds="100" timeToLiveSeconds="200" overflowToDisk="false" <!-- Only when it is configured as true can the hard disk storage be supported --> memoryStoreEvictionPolicy="LFU" />
As the name suggests, LRU and LFU focus on the last access time and frequency respectively. Let's take LFU as an example. Now we set the maximum storage to 3 records, that is, number 6-8. Now we access number 6 three times, number 7 twice, number 8 once, and will not issue SQL statements. We access number 7 again and issue SQL statements. Now number 7 is in the cache, number 8 has been removed because it has the least number of accesses. We can click number 8 again to test it, issue the SQL statement, and the test is successful. If it is an LRU, the number 6 just removed is number 6 because number 6 is the earliest accessed.
At this point, I believe everyone has mastered the use of the secondary cache, and the test of the secondary cache ends here. Let’s make configurations for our online mall project.
4. Actual configuration of online mall projects
We configure the maximum number of records in the secondary cache to be 1000, set the life cycle to 120 seconds and the interval cycle to 60 seconds. We support hard disk storage, and use the frequency priority (LFU) replacement strategy, because if the user click rate is high, it must be placed in the secondary cache.
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd"> <!-- If cache memory overflows, store it to hard disk space --> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="120" overflowToDisk="true" memoryStoreEvictionPolicy="LFU" /> </ehcache>
Well, in combination with the online mall project, the configuration and use of Hibernate 4.3's second-level cache is introduced.
Original address: http://blog.csdn.net/eson_15/article/details/51405911
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.