Пример Ehcache Привет, мир

Ehcache привет пример мира

ehcache-logo

В этом руководстве мы покажем вам два примера, которые помогут вам начать работу сEhcache.

Используемые инструменты:

  1. Ehcache 2.9

  2. Maven 3

  3. Gradle 2

  4. JDK 1,7

P.S Ehcache required JDK 1.5 or above.

1. Структура каталога проекта

ehcache-hello-world.

2. Привет, мир

Предположим, что это проект Maven:

pom.xml

    
        net.sf.ehcache
        ehcache
        2.9.0
    

Читайте комментарии для самоочевидных.

HelloEhCache.java

package com.example.cache;

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

public class HelloEhCache{

    public static void main(String[] args) {

        //1. Create a cache manager
        CacheManager cm = CacheManager.getInstance();

        //2. Create a cache called "cache1"
        cm.addCache("cache1");

        //3. Get a cache called "cache1"
        Cache cache = cm.getCache("cache1");

        //4. Put few elements in cache
        cache.put(new Element("1","Jan"));
        cache.put(new Element("2","Feb"));
        cache.put(new Element("3","Mar"));

        //5. Get element from cache
        Element ele = cache.get("1");

        //6. Print out the element
        String output = (ele == null ? null : ele.getObjectValue().toString());
        System.out.println(output);

        //7. Is key in cache?
        System.out.println(cache.isKeyInCache("1"));
        System.out.println(cache.isKeyInCache("5"));

        //8. shut down the cache manager
        cm.shutdown();

    }

}

Выход

06:03:37.007 [main] WARN  n.s.e.config.ConfigurationFactory - No configuration found.
    Configuring ehcache from ehcache-failsafe.xml  found in the classpath:
//...

Jan
true
false

//...

Note
Дополнительная информация об API, обратитесь к этомуPerforming Basic Cache Operations

Note
Фреймворк Ehcache можно настроить с помощью файлаehcache.xml, если этот файл недоступен, будет использоваться значение по умолчаниюehcache-failsafe.xml.

2. Конфигурация Ehcache

В этом примере мы покажем вам, как настроить Ehcache с помощью файлаehcache.xml.

Предположим, что это проект Gradle:

gradle.build

apply plugin: 'java'
apply plugin: 'eclipse-wtp'

version = '1.0'

// Uses JDK 7
sourceCompatibility = 1.7
targetCompatibility = 1.7

// Get dependencies from Maven central repository
repositories {
    mavenCentral()
}

//Project dependencies
dependencies {
    compile 'net.sf.ehcache:ehcache:2.9.0'
}

Создайтеehcache.xml и поместите его в папкуsrc/main/resources.

src/main/resources/ehcache.xml



    
    

    
    

    
    
        
    

Чтобы понять больше, прочтите этот официальный примерehcache.xml.

HelloEhCache.java

package com.example.cache;

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

public class HelloEhCache{

    public static void main(String[] args) {

        //1. Create a cache manager
        CacheManager cm = CacheManager.newInstance();

        //cm.addCache("cache1");

        //2. Get a cache called "cache1", declared in ehcache.xml
        Cache cache = cm.getCache("cache1");

        //3. Put few elements in cache
        cache.put(new Element("1","Jan"));
        cache.put(new Element("2","Feb"));
        cache.put(new Element("3","Mar"));

        //4. Get element from cache
        Element ele = cache.get("2");

        //5. Print out the element
        String output = (ele == null ? null : ele.getObjectValue().toString());
        System.out.println(output);

        //6. Is key in cache?
        System.out.println(cache.isKeyInCache("3"));
        System.out.println(cache.isKeyInCache("10"));

        //7. shut down the cache manager
        cm.shutdown();

    }

}

Выход

06:45:56.294 [main] DEBUG n.s.e.config.ConfigurationFactory -
  Configuring ehcache from ehcache.xml found in the classpath:
  file:/C:/Users/example/workspace2/JavaCache/target/classes/ehcache.xml
//...

Feb
true
false

//...

Note
Подробнее оLoading a Configuration

Скачать исходный код

Скачать -Java-Ehcache-HelloWorld-Example.zip (11 КБ)