spingboot第三方util形式整合ehcache

ehcache的各种原理,应用都不介绍了,官网里有,其他博客一大堆。您可以快速查阅,这篇博客纯属笔记。

开始使用要在application.java的开始代码中添加@EnableCaching注解

@SpringBootApplication
@EnableCaching
public class Application

在application.yml中添加cache内容

spring:
  cache:
    type: ehcache
    ehcache:
        config: classpath:ehcache.xml

pom引入依赖

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
  <version>2.8.3</version>
</dependency>

注解形式使用cache

//查询缓存
@Cacheable(value = "album_search", key = "#type")
public List<String>countStory(String type)

//刷新清除所有缓存
@CacheEvict(value = "album_search", allEntries = true)
public void clearHotSongCache() {}

代码中的value是ehchache.xml中的name

<cache name= "album_search"
           maxElementsInMemory= "1000"
           eternal= "false"
           timeToIdleSeconds= "180"
           timeToLiveSeconds= "86400"
           overflowToDisk= "false" />

整个的ehcache.xml配置
xml中的各种属性,不会的可以百度;着重注意一下是eternal,如果是false就是这个内存是定时的,timeToIdleSeconds, timeToLiveSeconds才会有用。

<ehcache>
    <diskStore path ="java.io.tmpdir"/>
    <defaultCache maxElementsInMemory= "10000"
                   eternal= "false"
                   timeToIdleSeconds= "120"
                   timeToLiveSeconds= "120"
                   overflowToDisk= "true"
                   diskSpoolBufferSizeMB= "30"
                   maxElementsOnDisk= "1000000"
                   diskPersistent= "false"
                   diskExpiryThreadIntervalSeconds="120"
                   memoryStoreEvictionPolicy= "LRU"  />

    <cache name= "album_search"
           maxElementsInMemory= "1000"
           eternal= "false"
           timeToIdleSeconds= "180"
           timeToLiveSeconds= "86400"
           overflowToDisk= "false" />
</ehcache>

第三方cacheutil代码

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * 

description: ehcache缓存工具类 * ALBUM_SEARCH是配置在ehcache.xml中的cacheName *

* * @author chenrui * @since 2018-07-17 */
public class QQAlbumEhcacheUtil { private static CacheManager cacheManager = CacheManager.create(); private static final String ALBUM_SEARCH = "album_search"; public static Object get(Object key) { Cache cache = cacheManager.getCache(ALBUM_SEARCH); if(cache!= null) { Element element = cache.get(key); if(element != null) { return element.getObjectValue(); } } return null; } public static void put(Object key, Object value) { Cache cache = cacheManager.getCache(ALBUM_SEARCH); if (cache != null) { cache.put(new Element(key, value)); } } public static boolean remove(Object key) { Cache cache = cacheManager.getCache(ALBUM_SEARCH); if (cache != null) { return cache.remove(key); } return false; } public static void main(String[] args) { String key = "key"; String value = "hello"; QQAlbumEhcacheUtil.put(key, value); QQAlbumEhcacheUtil.get(key); } }

你可能感兴趣的:(实际开发笔记)