美文网首页
Java的缓存框架ehcache

Java的缓存框架ehcache

作者: Felix_Fang | 来源:发表于2019-01-20 23:28 被阅读0次

    JVM内置缓存。
    流程大致就是,查询某个数据,先查询缓存有没有,没有就查数据库,然后把数据添加到缓存,如果缓存有,就不用查询数据库。

    缓存的一个过期策略:

    FIFO:First In First Out,先进先出。判断被存储的时间,离目前最远的数据优先被淘汰。
    LRU:Least Recently Used,最近最少使用。判断最近被使用的时间,目前最远的数据优先被淘汰。
    LFU:Least Frequently Used,最不经常使用。在一段时间内,数据被使用次数最少的,优先被淘汰。
    默认是使用第二种:LRU。下面有介绍各种参数的意思

    引入依赖:版本2倾向于单机处理,版本3倾向于分布式。

    <!-- 缓存技术,基于计算机内存的 -->
            <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache-core -->
            <dependency>
                <groupId>net.sf.ehcache</groupId>
                <artifactId>ehcache-core</artifactId>
                <version>${ehcache-core.version}</version>
            </dependency>
    

    引入ehcache.xml。这个要放在resources根目录下

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
             updateCheck="false">
        <!--
           diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
           user.home – 用户主目录
           user.dir  – 用户当前工作目录
           java.io.tmpdir – 默认临时文件路径
         -->
        <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
        <!--
           defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
         -->
        <!--
          name:缓存名称。
          maxElementsInMemory:缓存最大数目
          maxElementsOnDisk:硬盘最大缓存个数。
          eternal:对象是否永久有效,一但设置了,timeout将不起作用。
          overflowToDisk:是否保存到磁盘,当系统当机时
          timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
          timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
          diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
          diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
          diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
          memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
          clearOnFlush:内存数量最大时是否清除。
          memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
          FIFO,first in first out,这个是大家最熟的,先进先出。
          LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
          LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
       -->
        <defaultCache
                eternal="false"
                maxElementsInMemory="10000"
                overflowToDisk="false"
                diskPersistent="false"
                timeToIdleSeconds="1800"
                timeToLiveSeconds="259200"
                memoryStoreEvictionPolicy="LRU"/>
     
        <cache
                name="这里写一个自定义缓存策略名字,如:cloud_user"
                eternal="false"
                maxElementsInMemory="5000"
                overflowToDisk="false"
                diskPersistent="false"
                timeToIdleSeconds="1800"
                timeToLiveSeconds="1800"
                memoryStoreEvictionPolicy="LRU"/>
    //还可以继续写缓存,换个名字就行了
    </ehcache>
    

    导入ehcache的工具类

    List<User> list = null;//写一些数据
    //调用工具类把数据放入缓存。存活时间:60s,单位秒
    EhcacheUtil.setValue("cloud_fblog", "user_hotusers", list, 60);
    //取出缓存数据,get它的Key就行了。
    list = (List<User>) EhcacheUtil.getValue("刚刚写的那个缓存库名字cloud_user", "定义一个缓存名字:user_hotusers");
    

    Spring Boot 整合 Ehcache

    pom.xml和加入ehcache.xml(上面有)

            <!--开启 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>
            </dependency>
    

    application.properties的配置

    spring.cache.type=ehcache
    spring.cache.ehcache.cofnig=classpath:/ehcache.xml
    

    在入口处配置:

    @EnableCaching //开启ehcache缓存模式
    public class app {
        public static void main(String[] args) {
            app.run(app.class, args);
        }
    }
    

    在你需要缓存的类上面加入策略名称:

    //这里的名称要和你ehcache.xml里面配置的一样
    @CacheConfig(cacheNames = "cloud_user") //表示创建缓存配置,里面还有一些参数可以配置
    public class APIServiceImpl implements APIService {
    
    在类下面的方法那个需要缓存的加入注解@Cacheable
        @Cacheable //这个方法就已经加入缓存了
        public List<User> findByHotUser(Integer maxResults) {
            List<User> list = null;
            Pageable pageable = PageRequest.of(0, maxResults,Direction.DESC,"createTime");
            Page<User> page = userDao.findAll(pageable);
            list = page.getContent();
    

    缓存和DB不同步的问题:

    该数据已经在缓存里面,而且还没过期,这时候修改数据库,就会造成数据库和缓存数据不一致的问题。
    解决办法:在修改数据库的时候,顺便把缓存清理一下就可以了。

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

    ehcache集群:

    ehcache可以做,但是不合适做。
    在ehcache.xml里面加入代码:

    创建一个rmi的集群,端口号port8080、
        <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
            properties="hostName=127.0.0.1,port=8080,socketTimeoutMillis=120000" />
    
    这里端口号8081他会集群到8080,
        <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=manual,rmiUrls=//127.0.0.1:8081/cache_user"/>
    

    同样在另外一台服务器也做同样的配置,只不端口号和地址需要反过来。
    这样如果其中一台缓存发生变化,就会发送通知给另外一台。只不过如果服务器越多,配置就越多,不合适做集群。

    相关文章

      网友评论

          本文标题:Java的缓存框架ehcache

          本文链接:https://www.haomeiwen.com/subject/awzfjqtx.html