[] Ehcache learning the basics

A, Ehcache Overview

1.1 Introduction

Ehcache is open source caching framework pure java, fast, lean, etc., Hibernate is the default CacheProvider. It is mainly for common caching, Java EE and lightweight containers, with memory and disk storage, cache loaders, cache extensions, cache exception handler.
Ehcache originally started in 2003, developed by Greg Luck. In 2009, the project was purchased Terracotta. Still open source software, but some of the major new features (for example, can quickly restart of consistency between) can only be used in commercial products.
Ehcache are widely used in Hibernate, Spring, Cocoon and other open source systems.

The main characteristic of 1.2 Ehcache

  1. fast;
  2. simple;
  3. A variety of caching policy;
  4. There are two levels of data cache: memory and disk, so no need to worry about capacity issues;
  5. Cached data is written to disk in the process of restarting the virtual machine;
  6. By RMI, etc. can be inserted into the distributed API caches;
  7. Listening cache and cache manager with an interface;
  8. Cache Manager supports multiple instances, and one example of a plurality of cache area;
  9. Hibernate provides cache implementation;

Two, Ehcache use Description

  Ehcache is a tool used to manage the cache, the cached data may be stored in memory inside, may be stored on the hard disk. Its core is CacheManager, all applications are Ehcache CacheManager began. It is used to manage Cache (cache), and an application can have multiple CacheManager, and the next CacheManager and can have multiple Cache. Cache is stored inside one of the Element, and saved a pair Element is a key and value, the equivalent of a Entry Map inside.

2.1 Ehcache cache expiration policy

  When the cache needs to be cleaned (such as the space occupied already close to the threshold a), requires the use of some kind of elimination algorithm to determine what data is cleared away. Elimination algorithm commonly used are the following categories:

  1. FIFO: First In First Out, FIFO. Analyzing the stored time, farthest from the current priority of the data is eliminated.
  2. LRU: Least Recently Used, the least recently used. Determine the most recent time being used, the current farthest priority data is eliminated.
  3. LFU: Least Frequently Used, most do not often use. Period of time, the least number of times data is used, preferentially eliminated.

2.2 How to solve the problem with the db cache are not synchronized.

Cache problem with the db-sync will happen under what scenario the project
in a production environment, it is impossible to arbitrarily change the database value directly.
update (modify) or del (delete)

  1. Restart the server directly
  2. Proactive notification

update later statement with proactive notification.
To modify, after the modification is successful, the initiative to clean up the cache, which is in the same transaction.
Ah clear the cache and then change over in case of failure to modify it?
JOB regular health checks

Three, Ehcache basic project presentation

SpringBoot2.0 integration framework Ehcache

3.1 Maven environment dependent

<!--开启 cache 缓存 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache缓存 -->
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>2.9.1</version><!--$NO-MVN-MAN-VER$ -->
</dependency>  

3.2 YML profile information

###端口号配置
server:
  port: 8081
###数据库配置  
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:
    type: ehcache
    ehcache:
      config: classpath:app1_ehcache.xml

3.3 App startup mode

@MapperScan(basePackages = { "com.itmayiedu.mapper" })
@EnableCaching
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}
// @EnableCaching 开启ehcache缓存模式

3.4 Use Project

@CacheConfig(cacheNames = "userCache")
public interface UserMapper {
    @Select("SELECT ID ,NAME,AGE FROM member where id=#{id}")
    @Cacheable
    List<Users> getUser(@Param("id") Long id);
}    
//@Cacheable  加了该注解的方法表示可以缓存
//@CacheConfig 表示创建缓存配置,Key为userCache

3.5 EhCache Configuration

app1_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">

    <diskStore path="java.io.tmpdir/ehcache-rmi-4000" />

    <!-- 默认缓存 -->
    <defaultCache maxElementsInMemory="1000" eternal="true"
        timeToIdleSeconds="120" timeToLiveSeconds="120" overflowToDisk="true"
        diskSpoolBufferSizeMB="30" maxElementsOnDisk="10000000"
        diskPersistent="true" diskExpiryThreadIntervalSeconds="120"
        memoryStoreEvictionPolicy="LRU">
    </defaultCache>

    <!-- demo缓存 -->
    <cache name="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" />
        <!-- 用于在初始化缓存,以及自动设置 -->
        <bootstrapCacheLoaderFactory
            class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory" />
    </cache>
</ehcache>

Parameters related to the configuration instructions:

  1. diskStore标签:指定数据存储位置,可指定磁盘中的文件夹位置( 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标签:默认的管理策略,Ehcache 使用Map集合实现的 element 其实就是 key 和value

  • 以下属性是必须的:
    • 1、name: Cache的名称,必须是唯一的(ehcache会把这个cache放到HashMap里)。
    • 2、maxElementsInMemory:在内存中缓存的element的最大数目。
    • 3、maxElementsOnDisk:在磁盘上缓存的element的最大数目,默认值为0,表示不限制。
    • 4、eternal:设定缓存的elements是否永远不过期。如果为true,则缓存的数据始终有效,如果为false那么还要根据timeToIdleSeconds,timeToLiveSeconds判断。
    • 5、overflowToDisk: 如果内存中数据超过内存限制,是否要缓存到磁盘上。
  • 以下属性是可选的:
    • 1、timeToIdleSeconds: 对象空闲时间,指对象在多长时间没有被访问就会失效。只对eternal为false的有效。默认值0,表示一直可以访问。
    • 2、timeToLiveSeconds: 对象存活时间,指对象从创建到失效所需要的时间。只对eternal为false的有效。默认值0,表示一直可以访问。
    • 3, diskPersistent: whether persisted on disk. Jvm refers to restart after the data is valid. The default is false.
    • 4, diskExpiryThreadIntervalSeconds: object detection thread run intervals. Thread identifies the object's state how long run once.
    • 5, diskSpoolBufferSizeMB: disk size DiskStore use the default value of 30MB. Each cache using their DiskStore.
    • 6, memoryStoreEvictionPolicy: If the policy when the data memory exceeds memory limits, the cache to disk. Default LRU, optional FIFO, LFU.

3.6 Clear Cache

@Autowired
private CacheManager cacheManager;
@RequestMapping("/remoKey")
public void remoKey() {
  cacheManager.getCache("userCache").clear();
}

  

Four, Ehcache cluster model

  Since EhCache is in the process of caching system, once the application deployment in a clustered environment, each node maintains its own cache data, when a node cache data is updated, the updated data can not be shared in other nodes, which not only It will reduce the efficiency of the node is running, and will not lead to data synchronization occurs. For example a site using A, B two nodes as a cluster deployment, when the cache update A node, while the node B may cache has not been updated when users browse the page appears, one will be updated data, one will be the data has not been updated, although we can also lock users on a node, but for some interactive system relatively strong or non-Web-speaking, Session Sticky obviously not suitable by Session Sticky technology.

4.1 Project Configuration

  The above app1_ehcache.xml copy, named app2_ehcache.xml
two XML files are added as follows:

app1_ehcache.xml:


<!-- 多台机器配置 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>
<!-- 配置 rmi 集群模式 -->
<cacheManagerPeerListenerFactory
    class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
    properties="hostName=127.0.0.1,port=4000,socketTimeoutMillis=120000" />

<!-- 多播方式配置 搜索某个网段上的缓存 timeToLive 0是限制在同一个服务器 1是限制在同一个子网 32是限制在同一个网站 64是限制在同一个region 
    128是限制在同一个大洲 255是不限制 <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" 
    properties="peerDiscovery=automatic, multicastGroupAddress=224.1.1.1, multicastGroupPort=40000, 
    timeToLive=32" /> -->

app2_ehcache.xml:

<!-- 多台机器配置 -->
<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" />

<!-- 多播方式配置 搜索某个网段上的缓存 timeToLive 0是限制在同一个服务器 1是限制在同一个子网 32是限制在同一个网站 64是限制在同一个region 
    128是限制在同一个大洲 255是不限制 <cacheManagerPeerProviderFactory class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory" 
    properties="peerDiscovery=automatic, multicastGroupAddress=224.1.1.1, multicastGroupPort=40000, 
    timeToLive=32" /> -->

4.2 Test Project

Yml to modify the files are 8080 and 8081 ports + app1_ehcache.xml port + app2_ehcache.xml start SpringBoot items:

  • 1. The data in the database:

  • 2. Access http://127.0.0.1:8080/getUser?id=2can normally be found in the data:

  • 3. Access http://127.0.0.1:8081/getUser?id=2can be found in the normal data

  • 4. Direct manually modify data in the database:

  • 5. In the above-described access interface discovery, or check out the data name "Ming", the reason is because the cache sake
  • 6. Call clear the cache interface http://127.0.0.1:8080/remoKey, the cache is cleared at this time pay attention to port 8080,
  • 7. calls this interface http://127.0.0.1:8080/getUser?id=2, you can re-query the database to a value of "Xiao Ming", but can be found in the 8081 cache port is cleared, and this is the reason EhCache cluster configuration.


4.3 Common cluster model

  EhCache from the 1.7 version, supports five cluster solution, namely: Terracotta, RMI, JMS, JGroups, EhCache Server

RMi cluster model

How do you know that other cache cluster environment?
What is the message delivered in the form of distributed?
What needs to be replicated? Increase (Puts), update (Updates) or failure (Expiries)?
What way replication? Synchronous or asynchronous mode?

  • 1, correct element type: Only serializable elements can be copied. Some operations, such as removing, only the key values ​​required elements without the entire element; such an operation, even if the element is not serializable key is serializable, but may also be replicated.
  • 2、成员发现(Peer Discovery):Ehcache进行集群的时候有一个cache组的概念。每个cache都是其他cache的一个peer,没有主cache的存在。成员发现(Peer Discovery)正是用来解决 “你如何知道集群环境中的其他缓存?” 这个问题的。Ehcache提供了两种机制用来进行成员发现,即:自动成员发现和手动成员发现。要使用一个内置的成员发现机制要在ehcache的配置文件中指定cacheManagerPeerProviderFactory元素的class属性为 net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory。

4.4 Ehcache的使用场景

  • 使用纯java的ehcache作为本地缓存
  • Reids 作为远程分布式缓存
  • 解决redis缓存压力过大,提高缓存速度,以及缓存性能。

4.5 Redis和Ehcache缓存的区别

  • 如果是单个应用或者对缓存访问要求很高的应用,用ehcache。
  • 如果是大型系统,存在缓存共享、分布式部署、缓存内容很大的,建议用redis。

4.6 实际工作中使用Ehcache

  • 我们在项目中使用集中式缓存(Redis或者式Memcached等),通常都是检查缓存中是否存在
  • 期望值的数据,如果存在直接返回,如果不存在就查询数据库让后在将数据库缓存,

  • 这个时候如果缓存系统因为某写原因宕机,造成服务无法访问,那么大的量请求直接穿透到数据库,最数据库压力非常大。

  • 这时候我们让ehcache作为二级缓存,当redis服务器宕机后,可以查询ehcache缓存。

  • 这样能够有效的扛住服务器请求压力。

Guess you like

Origin www.cnblogs.com/haoworld/p/ehcache-ji-chu-zhi-shi-xue-xi.html