EHCache cache for Hibernate performance optimization, hibernateehcache
Compared with JDBC operations, ORM frameworks such as Hibernate require more complex mechanisms for ing and object state management. Therefore, there is a certain loss in performance and efficiency.
Besides ensuring that ing is avoided to produce inefficient SQL operations, cache is one of the keys to improving Hibernate.
Adding cache can avoid connection creation and destruction, data packaging and unpacking, SQL Execution, and network transmission caused by database calls. A good cache mechanism and a reasonable cache mode can greatly improve the performance, EHCache provides such a good caching mechanism.
Before you consider adding cache to the system for optimization, reusing SessionFactory is the best and most basic performance optimization method for Hibernate. For details, refer to the previous article "SessionFactory reuse for Hibernate performance optimization".
Hibernate Cache Mechanism
Cache levels are generally divided into three types, each of which has a larger scope:
Transaction-level cache: the cache object is shared in a Session, which is called a level-1 cache in Hibernate;
Application-level cache: Hibernate is called a second-level cache. It shares cache objects in a SessionFactory and SessionFactory is reused throughout the application;
Distributed cache: deployed as a separate instance, such as Redis and Memcache.
Hibernate caches data as follows:
When Hibernate accesses the Data Object Based on the ID, it first queries the data object from the Session level cache;
No. If the second-level cache is configured, the second-level cache is used;
If none of them are found, query the database again, and then update the cache when the results are deleted, updated, and added to the cache by ID.
Hibernate does not enable secondary cache by default. EHCache is a secondary cache plug-in Hibernate. The Hibernate system can directly use EHCache for caching.
Why use EHCache directly?
Looking back, a good cache mechanism and a reasonable cache mode can greatly improve the performance.
What is the cache mode of Hibernate?
Cache objects by ID, that is, the get and load operations of the Session.
There are two drawbacks of this cache mode:
1. The application scenario is too simple, and a large number of batch query caches in the system do not play a role;
2. In some systems, sessions are reused through ThreadLocal threads. Each thread may need to process a large number of unused business logic, and the cache hit rate is very low. If sessions are not reused, the cache hit rate is lower in general scenarios.
Since EHCache has provided a good caching mechanism, it is best to optimize the cache mode based on the business of your system.
How to Use EHCache
EHCache is a second-level cache plug-in Hibernate. You can directly use EHCache cache in Hibernate systems without adding other jar packages.
Create an EHCache configuration file. For more information, see the manual:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"> <diskStore path="java.io.tmpdir"/> <defaultCache maxElementsInMemory="10000" maxElementsOnDisk="0" eternal="true" overflowToDisk="true" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="0" diskSpoolBufferSizeMB="50" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LFU" /> <cache name="restCache" maxElementsInMemory="100" maxElementsOnDisk="0" eternal="false" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="119" timeToLiveSeconds="119" diskSpoolBufferSizeMB="50" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="FIFO" /> </ehcache>
One advantage of EHCache is thread security, which is suitable for multithreading scenarios and can simplify the use of developers.
Therefore, I wrote a singleton mode to avoid getCache every time in the method. This class also covers the basic usage of EHCache:
public class EHCacheFactory { private final CacheManager manager; private final Cache cache; private EHCacheFactory() { manager = CacheManager.create(getClass().getResource("/ehcache.xml")); cache = manager.getCache("restCache"); } public Element getCache(String strKey) { return EHCacheFactory.getInstance().getCache().get(strKey); } public void setCache(String strKey, String strVal) { EHCacheFactory.getInstance().getCache().put(new Element(strKey, strVal)); } public Cache getCache() { return cache; } private static class SingletonHolder { private final static EHCacheFactory INSTANCE = new EHCacheFactory(); } public static EHCacheFactory getInstance() { return SingletonHolder.INSTANCE; }}
My system is java rest. The EHCache cache is added to the REST interface to be buffered. The URL parameter is used as the cache key value, and the json data returned by the REST interface is used as the cache value, this cache mode is very suitable for REST.
A simple performance test was conducted using AB:
In a simple answer query interface, the performance is doubled;
In a slightly complex interface, when four or five queries are executed, the performance is improved by 20 times after the cache is added.
Here we will not post the AB test results. You can test it on your own.
Record, for better yourself!