Empezando con EhCache

EhCache es un marco de almacenamiento en caché en proceso de Java puro, que es rápido y capaz, y es el CacheProvider predeterminado en Hibernate. En comparación con el popular redis, debido a que se almacena directamente en la máquina virtual jvm, tiene las ventajas de velocidad rápida, alta eficiencia y múltiples estrategias de almacenamiento en caché, pero será mejor si es una aplicación distribuida.

El uso de EhCache es muy simple, aquí hay un ejemplo para ilustrar cómo usarlo en el proyecto.

1. Introduce la dependencia de maven

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

2. Está integrado con Spring, y la dependencia relevante de Spring
applicationContext-ehcache.xml debe agregarse de la siguiente manera:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:cache="http://www.springframework.org/schema/cache"  
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/cache 
        http://www.springframework.org/schema/cache/spring-cache.xsd"
       default-lazy-init="true">

    <description>Ehcache配置文件</description>

    <bean id="ehCacheManagerFactory"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:conf/cache/ehcache.xml"></property>
    </bean>
    <!-- 配置cache manager -->
    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager" ref="ehCacheManagerFactory" />
    </bean>
    <cache:annotation-driven />     

</beans>

3. información de configuración de la caché de ehcache, ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    updateCheck="false" monitoring="autodetect" dynamicConfig="true">
    <diskStore path="java.io.tmpdir" />
    <defaultCache 
        maxElementsInMemory="100"
        eternal="false" 
        timeToIdleSeconds="120" 
        timeToLiveSeconds="0"
        overflowToDisk="false" 
        diskPersistent="false"
        diskExpiryThreadIntervalSeconds="120" 
        memoryStoreEvictionPolicy="LRU" />

    <cache
            name="cacheName"
            maxElementsInMemory="500"
            eternal="false"
            timeToIdleSeconds="86400"
            timeToLiveSeconds="86400"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU" />
</ehcache>

La siguiente simulación es la primera vez que se obtiene de la base de datos, luego se guarda en la memoria caché y la segunda vez se obtiene de la memoria caché.

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext();
        Resource resource = ctx.getResource("classpath:/conf/cache/ehcache.xml");
        CacheManager cacheManager = EhCacheManagerUtils.buildCacheManager("default", resource);
        Cache cache = cacheManager.getCache("cacheName");
        Element element = cache.get("cacheKey");
        if(element == null){
            LOG.info("第一次缓存没有");
            Map<String, String> newMap = new HashMap<>();
            newMap.put("name", "科比");
            Element element1 = new Element("cacheKey", newMap);
            cache.put(element1);
        }

        new LoyaltyBusinessService().getFromCache(cacheManager);
    }

    public void getFromCache(CacheManager cacheManager){
        Cache cache = cacheManager.getCache("cacheName");
        Element element = cache.get("cacheKey");
        if(element != null){
            Map<String, String> fromMap = (Map<String, String>) element.getObjectValue();
            LOG.info("第二次从缓存拿到了{}", fromMap.get("name"));
        }
    }

Los resultados de la operación son los siguientes:
Escriba la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/huangdi1309/article/details/80932767
Recomendado
Clasificación