복붙노트

[SPRING] Spring을 사용하여 EhCache 인스턴스 가져 오기 ... 지능적으로

SPRING

Spring을 사용하여 EhCache 인스턴스 가져 오기 ... 지능적으로

특정 EhCache 인스턴스를 이름으로 가져와야하고 가능한 경우 자동 응답하는 것을 선호합니다. 다음과 같이 자동으로 구성된 컨트롤러가있는 경우, 찾고있는 캐시 인스턴스에서 어떻게 자동 배선 할 수 있습니까?

@Controller 
public class MyUniqueService {
    ...
}
<beans ...>
    <ctx:component-scan base-package="my.controllers"/>
    <mvc:annotation-driven />
</beans>

내 응용 프로그램 컨텍스트에서 EhCache를 어떻게 구성합니까? 내 / WEB-INF / 디렉토리에 ehcache.xml 파일을로드하는 것에 대한 EhCache의 로그 메시지가 표시되지 않습니다. 어떻게로드 할 수 있습니까?

내 Spring 응용 프로그램과 EhCache를 통합하여 my / WEB-INF / 디렉토리에서 ehcache.xml 파일을로드하고 MyUniqueService 컨트롤러에 주어진 이름의 캐시를 autowire하려면 어떻게합니까?

해결법

  1. ==============================

    1.먼저 다음과 같이 앱 컨텍스트에서 Ehcache CacheManager 싱글 톤을 생성해야합니다.

    먼저 다음과 같이 앱 컨텍스트에서 Ehcache CacheManager 싱글 톤을 생성해야합니다.

    <bean id="myEhCacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:my-ehcache.xml"/>
    </bean>
    

    여기서 configLocation은 classpath에서로드하거나 value = "/ WEB-INF / my-ehcache.xml"을 사용하도록 설정됩니다.

    컨트롤러에서 간단히 CacheManager 인스턴스를 삽입하십시오.

    @Controller 
    public class MyUniqueService {
    
        @Resource(name="myEhCacheManager")
        private CacheManager cacheManager;
    
        ...
    }
    

    또는 "완전히 자동으로 실행되는"경로로 이동하려면 다음을 수행하십시오.

    <bean class="org.springframework.cache.ehcache.EhCacheCacheManager">
        <property name="cacheManager">
            <bean class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
                <property name="configLocation" value="/WEB-INF/ehcache.xml"/>
            </bean>
        </property>
    </bean>
    

    다음과 같이 클래스를 설정하십시오.

    @Controller
    public class MyUniqueService { 
    
        @Autowired
        private org.springframework.cache.CacheManager cacheManager;
    
        public org.springframework.cache.Cache getUniqueObjectCache() {
            return cacheManager.getCache("uniqueObjectCache");
        }
    }
    

    uniqueObjectCache는 ehcache.xml 캐시 정의에있는이 캐시 인스턴스에 해당합니다.

    <cache name="uniqueObjectCache"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           memoryStoreEvictionPolicy="LRU"
           transactionalMode="off"/>
    

    실제 캐시 인스턴스를 삽입하는 방법은 없지만 위에 표시된 것처럼 캐시 관리자를 삽입하여이를 사용하여 관심있는 캐시를 가져올 수 있습니다.

  2. ==============================

    2.cacheManager가 정의되었다고 가정합니다.

    cacheManager가 정의되었다고 가정합니다.

    <bean id="cacheManager"
        class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation" value="classpath:/ehcache.xml"/>
    </bean>
    

    다음과 같이 특정 캐시를 가져 오거나 삽입 할 수 있습니다.

    @Value("#{cacheManager.getCache('myCacheName')}")
    private Cache myCache;
    

    관심이 있다면 @Value () http://www.mkyong.com/spring3/spring-el-method-invocation-example/에서 Spring EL을 사용하는 방법에 대한 예제도 참조하십시오.

  3. ==============================

    3.컨텍스트가 올바른 클래스로 bean을 찾을 수 있으면 autowire를 사용할 수도 있습니다. 여기 내 XML을 구성하는 방법입니다.

    컨텍스트가 올바른 클래스로 bean을 찾을 수 있으면 autowire를 사용할 수도 있습니다. 여기 내 XML을 구성하는 방법입니다.

    <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
        <property name="configLocation">
            <value>WEB-INF/ehcache.xml</value>
        </property>
    </bean>
    
    <bean id="cache" class="net.sf.ehcache.Cache" factory-bean="cacheManager" factory-method="getCache">
        <constructor-arg value="CacheNameHere" />          
    </bean>
    

    그리고 내 자바 클래스

    @Autowired
    private net.sf.ehcache.Cache cache;
    

    이 설정은 나를 위해 작동합니다.

  4. ==============================

    4.과연! 또는 java config 클래스를 사용하려면 다음을 수행하십시오.

    과연! 또는 java config 클래스를 사용하려면 다음을 수행하십시오.

            @Inject
            private ResourceLoader resourceLoader;
    
            @Bean
            public CacheManager cacheManager() {
                EhCacheCacheManager ehCacheCacheManager = new EhCacheCacheManager();
                try {
                    ehCacheCacheManager.setCacheManager(ehcacheCacheManager().getObject());
                } catch (Exception e) {
                    throw new IllegalStateException("Failed to create an EhCacheManagerFactoryBean", e);
                }
                return ehCacheCacheManager;
            }
    
            @Bean
            public FactoryBean<net.sf.ehcache.CacheManager> ehcacheCacheManager() {
                EhCacheManagerFactoryBean bean = new EhCacheManagerFactoryBean();
                bean.setConfigLocation(resourceLoader.getResource("classpath:ehcache.xml"));
                return bean;
            }
    
  5. from https://stackoverflow.com/questions/11462662/getting-an-ehcache-instance-with-spring-intelligently by cc-by-sa and MIT license