当前位置:网站首页>Local cache --ehcache
Local cache --ehcache
2022-07-25 15:21:00 【Literary youth learn programming】
1 What is? Ehcache
Ehcache Is pure java Open source caching framework , With fast 、 Characteristics such as ability , yes Hibernate In the default CacheProvider. It's mainly for general purpose caching 、Java EE And lightweight containers , With memory and disk storage 、 Cache loader 、 Cache extension 、 Cache exception handler .
Ehcache By the first Greg Luck On 2003 Development started in .2009 year , The project was Terracotta Buy . The software is still open source , But some of the new main features ( for example , Consistency between fast restartability ) Can only be used in commercial products .
Ehcache Is widely used in Hibernate、Spring、Cocoon Other open source systems .
2Ehcache The main characteristics of
1. Fast ;
2. Simple ;
3. Multiple caching strategies ;
4. There are two levels of caching data : Memory and disk , So there's no need to worry about capacity ;
5. The cached data will be written to disk during virtual machine restart ;
6. Can pass RMI、 Pluggable API And so on ;
7. Listening interface with cache and cache manager ;
8. Supports multiple cache manager instances , And multiple cache areas of an instance ;
9. Provide Hibernate Cache implementation of ;
3.Ehcache Introduction
Ehcache Is a tool for managing cache , The cached data can be stored in memory , It can also be stored on the hard disk . Its core is CacheManager, everything Ehcache All applications are from CacheManager At the beginning . It is used to manage Cache( cache ) Of , An application can have multiple CacheManager, And one CacheManager There can be more than one Cache.Cache The internal storage is one by one Element, And one Element Saved in is a key and value Pairing of , amount to Map One of the inside Entry.
4.Ehcache Cache expiration policy
When the cache needs to be cleaned up ( For example, the space occupation is close to the critical value ), You need to use some sort of culling algorithm to decide which data to clean up . There are several common elimination algorithms :
FIFO:First In First Out, fifo . Judge the stored time , The data farthest away from the present will be eliminated first .
LRU:Least Recently Used, Recently at least use . Judge the last time used , At present, the farthest data is preferentially eliminated .
LFU:Least Frequently Used, The least used . Over a period of time , Data is used the least , Priority to be eliminated .
Ehcache Basic usage
Maven Environment depends on
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <!-- SpringBoot Yes lombok Support --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- SpringBoot web Core components --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </dependency> <!-- SpringBoot external tomcat Support --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <!-- springboot-log4j --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j</artifactId> <version>1.3.8.RELEASE</version> </dependency> <!-- springboot-aop technology --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.47</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Turn on cache cache --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <!-- ehcache cache --> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.9.1</version><!--$NO-MVN-MAN-VER$ --> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql rely on --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> </dependencies> |
YML Profile information
### Port number configuration server: port: 8081 ### Database configuration spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: root driver-class-name: com.mysql.jdbc.Driver test-while-idle:true test-on-borrow:true validation-query: SELECT 1 FROM DUAL time-between-eviction-runs-millis: 300000 min-evictable-idle-time-millis: 1800000 # Cache configuration read cache: type: ehcache ehcache: config:classpath:app2_ehcache.xml |
App Starting mode
@MapperScan(basePackages = { "com.itmayiedu.mapper" }) @EnableCaching @SpringBootApplication publicclass App {
publicstaticvoid main(String[] args) { SpringApplication.run(App.class, args); }
} |
@EnableCaching Turn on ehcache Cache mode
Project use
@CacheConfig(cacheNames = "userCache") publicinterface UserMapper { @Select("SELECT ID ,NAME,AGE FROM users where id=#{id}") @Cacheable List<Users> getUser(@Param("id") Long id); } |
@Cacheable The annotated method indicates that it can cache
@CacheConfig Indicates creating a cache configuration ,Key by userCache
EhCache To configure
app1_ehcache
<?xmlversion="1.0"encoding="UTF-8"?> <ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStorepath="java.io.tmpdir/ehcache-rmi-4000"/>
<!-- Multiple machine configurations rmiUrls=//192.168.8.32:400002/demoCache|//192.168.5.231:400003/demoCache --> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:5000/userCache"> </cacheManagerPeerProviderFactory> <!-- To configure rmi Cluster pattern --> <cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=127.0.0.1,port=4000,socketTimeoutMillis=120000"/>
<!-- Multicast mode configuration Search the cache on a network segment timeToLive 0 Is limited to the same server 1 Is restricted to the same subnet 32 Is limited to the same website 64 Is limited to the same region 128 Is limited to the same continent 255 There is no limit <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic, multicastGroupAddress=224.1.1.1, multicastGroupPort=40000, timeToLive=32" /> -->
<!-- The default cache --> <defaultCachemaxElementsInMemory="1000"eternal="true" timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true" diskSpoolBufferSizeMB="30"maxElementsOnDisk="10000000" diskPersistent="true"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache>
<!-- demo cache --> <cachename="userCache"maxElementsInMemory="1000"eternal="false" timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true" diskSpoolBufferSizeMB="30"maxElementsOnDisk="10000000" diskPersistent="false"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/> <!-- Used to initialize the cache , And automatic setting --> <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/> </cache> </ehcache> |
app2_ehcache
<?xmlversion="1.0"encoding="UTF-8"?> <ehcachexmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStorepath="java.io.tmpdir/ehcache-rmi-5000"/>
<!-- Multiple machine configurations --> <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:4000/userCache"> </cacheManagerPeerProviderFactory>
<cacheManagerPeerListenerFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" properties="hostName=127.0.0.1,port=5000,socketTimeoutMillis=120000"/>
<!-- Multicast mode configuration Search the cache on a network segment timeToLive 0 Is limited to the same server 1 Is restricted to the same subnet 32 Is limited to the same website 64 Is limited to the same region 128 Is limited to the same continent 255 There is no limit <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" properties="peerDiscovery=automatic, multicastGroupAddress=224.1.1.1, multicastGroupPort=40000, timeToLive=32" /> -->
<!-- The default cache --> <defaultCachemaxElementsInMemory="1000"eternal="true" timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true" diskSpoolBufferSizeMB="30"maxElementsOnDisk="10000000" diskPersistent="true"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> </defaultCache>
<!-- demo cache --> <cachename="userCache"maxElementsInMemory="1000"eternal="false" timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true" diskSpoolBufferSizeMB="30"maxElementsOnDisk="10000000" diskPersistent="false"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"> <cacheEventListenerFactory class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"/> <!-- Used to initialize the cache , And automatic setting --> <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/> </cache> </ehcache> |
Clear cache
@Autowired private CacheManager cacheManager;
@RequestMapping("/remoKey") publicvoid remoKey() { cacheManager.getCache("userCache").clear(); } |
Parameter related configuration
1、diskStore : Specify data (.data and .index) Storage location , You can specify the folder location on the disk The diskStore element is optional. It must be configured if you have overflowToDisk or diskPersistent enabled for any cache. If it is not configured, a warning will be issues and java.io.tmpdir will be used.
2、defaultCache : Default management strategy
Ehcache Use Map The collection implements element In fact, that is key and value
One 、 The following attributes are required :
1、name: Cache The name of , Must be unique (ehcache Will take this. cache Put it in HashMap in ).
2、maxElementsInMemory: Cached in memory element The maximum number of .
3、maxElementsOnDisk: Cached on disk element The maximum number of , The default value is 0, Means unrestricted .
4、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 .
5、overflowToDisk: If the data in memory exceeds the memory limit , Do you want to cache to disk .
Two 、 The following properties are optional :
1、timeToIdleSeconds: Object free time , 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 .
2、timeToLiveSeconds: Object lifetime , 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 .
3、diskPersistent: Whether to persist on disk . Restart jvm after , Is the data valid . The default is false.
4、diskExpiryThreadIntervalSeconds: Object detection thread run time interval . How often does the thread that identifies the state of an object run .
5、diskSpoolBufferSizeMB: DiskStore The size of the disk used , The default value is 30MB. Every cache Use the respective DiskStore.
6、memoryStoreEvictionPolicy: If the data in memory exceeds the memory limit , Policy when caching to disk . The default value is LRU, Optional FIFO、LFU.
Ehcache Cluster pattern
because EhCache It's the caching system in the process , Once the application is deployed in a cluster environment , Each node maintains its own cached data , When a node updates the cached data , These updated data cannot be shared among other nodes , This will not only reduce the efficiency of node operation , And it will cause the data to be out of sync . For example, a website uses A、B Two nodes are deployed as clusters , When A After the node's cache is updated , and B Before the node cache is updated, users may browse the page , Later, the updated data , There will be data that has not been updated , Although we can also pass Session Sticky Technology to lock users on a node , But for some interactive or right and wrong Web In terms of system ,Session Sticky Obviously not very suitable for .
Common cluster mode
EhCache from 1.7 Version start , Five cluster schemes are supported , Namely :
Terracotta、RMI、JMS、JGroups、EhCache Server
RMi Cluster pattern
How do you know about other caches in a clustered environment ?
• What is the form of distributed messages ?
• What needs to be replicated ? increase (Puts), to update (Updates) Or failure (Expiries)?
• How to copy ? Synchronous or asynchronous ?
1、 Correct element type : Only serializable elements can be copied . Some operations , For example, remove , You only need the key value of the element, not the whole element ; In such an operation, even if the element is not serializable, but the key value is serializable, it can be copied .
2、 Members found that (Peer Discovery):Ehcache When clustering, there is a cache The concept of group . Every cache It's all other cache One of the peer, There is no lord cache The existence of . Members found that (Peer Discovery) It is used to solve “ How do you know about other caches in a clustered environment ?” Of this question .Ehcache Two mechanisms are provided for member discovery , namely : Automatic member discovery and manual member discovery . To use a built-in member discovery mechanism, you need to ehcache Specified in the configuration file of cacheManagerPeerProviderFactory Elemental class The attribute is
net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory.
Ehcache Usage scenarios of
Use pure java Of ehcache As a local cache
Reids As a remote distributed cache
solve redis Too much cache pressure , Improve cache speed , And cache performance .
Redis and Ehcache The difference between caching
If it is a single application or an application with high requirements for cache access , use ehcache.
If it's a large system , There is a cache share 、 Distributed deployment 、 The cache content is very large , Suggest using redis.
Used in practical work Ehcache
We use centralized caching in our projects (Redis Or Memcached etc. ), It's usually to check if there's any in the cache
Expected data , If there is a direct return , If it does not exist, query the database and cache the database ,
At this time, if the cache system goes down for some write reason , Make the service inaccessible , Such a large number of requests directly penetrate the database , The most database pressure is very high .
At this time we let ehcache As a second level cache , When redis When the server goes down , You can query ehcache cache .
This can effectively bear the pressure of server requests .
边栏推荐
猜你喜欢
随机推荐
CGO is realy Cool!
Understanding the execution order of T-SQL query from the execution order of join on and where
golang复习总结
Spark AQE
Spark SQL空值Null,NaN判断和处理
MySQL之事务与MVCC
单例模式3--单例模式
TypeScript学习2——接口
Es5 thinking of writing inheritance
C语言函数复习(传值传址【二分查找】,递归【阶乘,汉诺塔等】)
Docker上运行redis以配置文件方式启动,连接客户端报错Error: Server closed the connection
Idea远程提交spark任务到yarn集群
C#,C/S升级更新
Install entityframework method
How to finally generate a file from saveastextfile in spark
本地缓存--Ehcache
vscode 插件篇收集
NPM's nexus private server e401 E500 error handling record
Spark memory management mechanism new version
Instance Tunnel 使用









