Premiers pas avec EhCache

EhCache est une infrastructure de mise en cache en cours de processus Java pure, rapide et capable, et est le CacheProvider par défaut dans Hibernate. Comparé au redis populaire, car il est stocké directement dans la machine virtuelle jvm, il présente les avantages d'une vitesse rapide, d'une efficacité élevée et de plusieurs stratégies de mise en cache, mais ce sera mieux s'il s'agit d'une application distribuée.

L'utilisation d'EhCache est très simple, voici un exemple pour illustrer comment l'utiliser dans le projet.

1. Introduisez la dépendance maven

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

2. Il est intégré à spring, et la dépendance appropriée de spring
applicationContext-ehcache.xml doit être ajoutée comme suit:

<?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. Informations de configuration du cache 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 simulation suivante est la première fois à extraire de la base de données, puis à la mettre dans le cache, et la deuxième fois à la récupérer à partir du cache

    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"));
        }
    }

Les résultats de l'opération sont les suivants:
Écrivez la description de l'image ici

Je suppose que tu aimes

Origine blog.csdn.net/huangdi1309/article/details/80932767
conseillé
Classement