Some queries need to be used in the project, but the data is seldom modified but the query degree is very large. It is sometimes queried by frequency.
Regardless of whether the cache is for queries far greater than updates and insertions
MyBatis has its own cache, first-level cache is session level, level two cache is namespace.
Turn on the disadvantage of two level slow: 1) Only in a namespace operation of a single table, such as: User, and user_role two tables, if User_role modified, using the user's namespace to query the result is dirty data.
2) When updating one of these, the whole namespace will be refreshed. We actually know that it's OK to just refresh one.
Personally feel that the business layer control will be better.
I have 2 cases in my current project,
1) The business only inquires the last half hour data, the data frequently updates, will have the data to insert unceasingly. is some temporary performance data.
Scenario: Give a Ehcache, save the last half hour of data, set up scheduled tasks, the previous data batch storage. The query takes precedence in the cache.
2) database data is configuration type, such as user's personal information, and then need to use in many places. and the frequency of use is very large.
Scenario: The business layer uses the Ehcache and MyBatis caches. Of course, you can also write a Ehcache cache class to manipulate this cache. And then as the business grows and you feel a lot of table data need this kind of caching, you start thinking about life.
Write the Ehcache class separately and save the data.
Spring-boot +mybaits +ehcache (cache annotation, where you want to put it.) If consider to directly modify the database, write a backdoor, directly refresh the cache, pay attention to security! )
MAVEN builds.
Critical-dependent packages (specific versions are up-to-date)
<Dependency> <groupId>Org.springframework</groupId> <Artifactid>Spring-context-support</Artifactid> </Dependency> <Dependency> <groupId>Net.sf.ehcache</groupId> <Artifactid>Ehcache</Artifactid> </Dependency>
Ehcache.xml Configuration
<?XML version= "1.0" encoding= "UTF-8"?><EhcacheXmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:nonamespaceschemalocation= "Http://ehcache.org/ehcache.xsd"UpdateCheck= "false"> <DiskstorePath= "User.dir/sqlehcache" /> <DefaultcacheEternal= "false"maxelementsinmemory= "+"Overflowtodisk= "false"diskpersistent= "false"Timetoidleseconds= "0"Timetoliveseconds= "All"Memorystoreevictionpolicy= "LRU" /> <Cachename= "Basecache"Eternal= "true"maxelementsinmemory= "+"Maxelementsondisk= "10000"Overflowtodisk= "true"diskpersistent= "false"Timetoidleseconds= "0"Timetoliveseconds= "+"Memorystoreevictionpolicy= "LRU" /></Ehcache>
(1). Diskstore: For the cache path, Ehcache is divided into memory and disk level two, this property defines the cache location of the disk. The parameters are explained as follows:
user.home– User Home Directory
user.dir– User's current working directory
java.io.tmpdir– Default Temporary file path
(2). Defaultcache: The default cache policy, which is used when Ehcache cannot find a defined cache. You can define only one.
(3). Cache: Custom cache policy for a custom cache policy. The parameters are explained as follows:
The cache element explains:
Properties of the cache element:
Name: Cache names
Maxelementsinmemory: Maximum number of cached objects in memory
Maxelementsondisk: The maximum number of cache objects on the hard disk, if 0 means infinity
Eternal:true indicates that the object never expires, the Timetoidleseconds and Timetoliveseconds properties are ignored, and the default is False
Overflowtodisk:true indicates that when the number of objects in the memory cache has reached
After the maxelementsinmemory bounds, the overflow object is written to the hard disk cache. Note: If the cached object is to be written to the hard disk, the object must implement the Serializable interface.
DISKSPOOLBUFFERSIZEMB: Disk buffer size, default is 30MB. Each cache should have its own cache.
Diskpersistent: Whether to cache the virtual machine Restart period data, whether to persist the disk cache, when the value of this property is true, the system will be initialized on the disk to find the file name is the cache name, the suffix named index file, This file holds the index of the cache that has been persisted on disk, and when found, it loads the cache into memory, to really persist the cache to disk, and to write the program with the Net.sf.ehcache.Cache.put (element element ) to call the Flush () method.
Diskexpirythreadintervalseconds: Disk failed thread run time interval, default is 120 seconds
Timetoidleseconds: Sets the maximum time, in seconds, that an object is allowed to be idle. When an object has been idle for longer than the Timetoidleseconds property value since the last time it was accessed, the object expires and Ehcache will empty it from the cache. This property is valid only if the Eternal property is false. If the property value is 0, the object can be idle indefinitely
Timetoliveseconds: The maximum amount of time, in seconds, that a set object is allowed to exist in the cache. When an object has been stored in the cache for more than the Timetoliveseconds property value, the object expires and Ehcache clears it from the cache. This property is valid only if the Eternal property is false. If the property value is 0, the object can exist indefinitely in the cache. Timetoliveseconds must be greater than timetoidleseconds attribute to make sense
Memorystoreevictionpolicy: When the maxelementsinmemory limit is reached, Ehcache will clean up the memory according to the specified policy. The optional policies are LRU (least recently used, default policy), FIFO (first in, out), LFU (minimum number of accesses).
Spring-boot injection, the Java code is mainly based on the configuration to generate the cache
Packagecom.configure;Importorg.springframework.cache.annotation.EnableCaching;ImportOrg.springframework.cache.ehcache.EhCacheCacheManager;ImportOrg.springframework.cache.ehcache.EhCacheManagerFactoryBean;ImportOrg.springframework.context.annotation.Bean;Importorg.springframework.context.annotation.Configuration;ImportOrg.springframework.core.io.ClassPathResource; @Configuration//The callout starts the cache@EnableCaching Public classcacheconfiguration {/** Ehcache main manager*/@Bean (Name= "Appehcachecachemanager") Publicehcachecachemanager Ehcachecachemanager (Ehcachemanagerfactorybean Bean) {return NewEhcachecachemanager (Bean.getobject ());} /** According to the settings of shared or not, Spring creates a ehcache base by Cachemanager.create () or new CacheManager () respectively. */@Bean PublicEhcachemanagerfactorybean Ehcachemanagerfactorybean () {Ehcachemanagerfactorybean CacheManagerFactoryBean=NewEhcachemanagerfactorybean (); Cachemanagerfactorybean.setconfiglocation (NewClasspathresource ("Ehcache.xml")); Cachemanagerfactorybean.setshared (true); returnCachemanagerfactorybean;}}
Then, using annotations, you can take advantage of the cache where you want it, and note that if there is a cache, you will not go the way it was.
Public InterfaceTransformerdao {/*** Delete all caches under this value, and the whole is refreshed *@paramstationoid *@return */@Caching (Evict={@CacheEvict (value= "Basecache", allentries=true)}) Public intDeletebystationoid (@Param ("Stationoid") String stationoid); /*** Check the variable-voltage group (device) information of the charging pile * *@parampileoid *@return */@Cacheable (Value= "Basecache", key = "#p0") PublicTransformer querytransformerbypileoid (@Param ("Pileoid") String pileoid);}
For @cacheable, @CachePut and @cacheevict Introduction, refer to:
http://blog.csdn.net/u014381863/article/details/48788199
There is a pit where you cannot directly use the parameter name as key
Only use #p this mode
Specific reasons for reference:
https://stackoverflow.com/questions/14197359/ Spring-cache-abstraction-vs-interfaces-vs-key-param-null-key-returned-for-cach
Spring-boot+mybatis+ehcache for fast Query