Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > Spring 3.1 + ehcache


Автор: stallman 13.4.2011, 12:28
Всем привет.

Хочется использовать кеширование в новом Spring 3.1

Собственно изучив http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/ сделал как описано, за исключение кеш-мененджера.
Прописал так:

cache-context.xml
Код

<?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"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/cache
            http://www.springframework.org/schema/cache/spring-cache.xsd">

    <cache:annotation-driven />

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"  p:cache-manager-ref="ehcache"/>
    <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:config-location="ehcache.xml" />

</beans>



Однако поучил пинок от спринга в виде :

Код

javax.servlet.ServletException: Servlet.init() for servlet dispatcher threw exception
    ...

java.lang.IllegalStateException: Could not create MetadataReader for class org.springframework.cache.ehcache.EhcacheCacheManager
    ...

java.io.FileNotFoundException: class path resource [org/springframework/cache/ehcache/EhcacheCacheManager.class] cannot be opened because it does not exist
    ...


Насколько я понял - не найден ehcache manager, однако про его присутствие в 3.1 заявляет как спринг, так и http://ehcache.org/documentation/spring.html

Где грабли ?

Автор: stallman 13.4.2011, 13:07
блииин.... =)


EhcacheCacheManager.class --> EhCacheCacheManager.class

Автор: stallman 13.4.2011, 13:43
Вроде заработало.

Но кешируемый метод все же не кешируется

Код

    @Cacheable("message")
    public String sampleCache(int id){
        LOG.info("--------------- call sampleCache() ");
        return "sample";
    }
     ....
     sampleCache(1);



Поидее при повторном вызове код метода вызываться не должен, но это происходит.

В конфигах ehcache не силен, посему остановился на

Код

<ehcache>
    <defaultCache />
    <cache name="message"/>
</ehcache>

Автор: stallman 13.4.2011, 15:23
Заставляет задуматься вот эта строчка http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html

Код

Note that just like other services in Spring Framework, the caching service is an abstraction (not a cache implementation)
and requires the use of an actual storage to store the cache data - that is, the abstraction frees the developer from having to
write the caching logic but does not provide the actual stores.


Добавлено через 2 минуты и 29 секунд
Следовательно возникает вопрос , что нужно имплементировать ?

Автор: MisterCleric 13.4.2011, 16:18
Привет. А заодно читаем дальше:
Цитата

There are two integrations available out of the box, for JDK java.util.concurrent.ConcurrentMap and Ehcache

Это и имеется в виду как готовая имплементация Storage для кешируемых результатов.

Добавлено через 1 минуту и 13 секунд
Плюс. Важно заметить, что кеширование результатов выполнения методов строго зависит от параметров. Т.е. при смене значений параметров результат уже не будет браться из кеша

Автор: stallman 13.4.2011, 16:30
Цитата(MisterCleric @  13.4.2011,  16:18 Найти цитируемый пост)
Плюс. Важно заметить, что кеширование результатов выполнения методов строго зависит от параметров. Т.е. при смене значений параметров результат уже не будет браться из кеша 

Это понятно.

Вобщем я понял (http://www.brucephillips.name/blog/index.cfm/2011/3/22/Spring-31-Cache-Implementation-With-Cacheable-and-CacheEvict-Annotations) что кешированию подлежат только спринг-объекты.

Собственно косяк был в том, что я пытался кешировать произвольный метод произвольного класса, а этого делать нельзя.



Автор: MisterCleric 13.4.2011, 16:50
Цитата

Вобщем я понял (источник) что кешированию подлежат только спринг-объекты.

Утверждение не верно: кешированию подлежат результаты выполнения методов Spring-бинов, а не сами бины.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)