공적's life

ehcache 적용하기 본문

Programing

ehcache 적용하기

melpis 2012. 6. 1. 11:04

일단 라이브러리 넣기

 

스프링과 같이 결합하여 사용하기 때문에 스프링 모듈도 넣어줘야 한다.

 

ehcache-core-2.5.2-distribution.tar 요고를 받아서 풀고 플러스로 spring-modules-cache-0.9.jar 요것도 넣어줘야함

 

이렇게 두개만 넣으면 라이브러리 준비끝

 

나머지는 되게 간단

 

스프링 설정 파일에

 

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

 

요렇게 넣고

 

실제 사용 될 클래스에 인젝션 해준후에

 

캐쉬에 넣는 방법은

 

Cache cache = cacheManager.getCache(cacheName);
   Element element = new Element(id, timestamp);
   cache.put(element);

 

이렇게 ~

 

꺼내는 법은

 

Cache cache = cacheManager.getCache(cacheName);
  if (cache.isKeyInCache(id)) {
   Element element = cache.get(id);
   element.updateAccessStatistics();
   String  value = (String)element.getObjectValue();
  
   }

 

이렇게 간단간단 중간에 updateAccessStatistics 이건 캐쉬를 읽었다는 소리 hit율 올리기

 

이렇게 사용하면 됩

 

이제 남은 한개 설정 파일

 

 

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd"
         updateCheck="true" monitoring="autodetect"
         dynamicConfig="true">
  
   <diskStore path="java.io.tmpdir"/>
  
   <cacheManagerPeerProviderFactory class=
                          "net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
                          properties="peerDiscovery=manual,
                          rmiUrls=//127.0.0.1:40000/authCache"
                          propertySeparator="," />
   <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
            properties="hostName=127.0.0.1, port=40001,socketTimeoutMillis=2000"/>
 
   
    <defaultCache maxElementsInMemory="500" eternal="false"
        overflowToDisk="true" timeToIdleSeconds="120" timeToLiveSeconds="120"
        diskPersistent="false" diskExpiryThreadIntervalSeconds="120" />
       
      <cache name="authCache"
           maxEntriesLocalHeap="10"
           eternal="false"
           timeToIdleSeconds="100"
           timeToLiveSeconds="0"
           overflowToDisk="false">
     <cacheEventListenerFactory
   class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
   properties="replicateAsynchronously=true, replicatePuts=true, replicateUpdates=true,
   replicateUpdatesViaCopy=false, replicateRemovals=true "/>
    </cache>

</ehcache>

이건 복제를 하기 위해서 설정해놓은 것 그러므로 복제 즉 동기화가 필요없을때는 위 에 factory 클래스는 필요 없음

 

그냥 캐쉬만 설정하면 됩니다.

 

overflowToDisk가 false이므로 위에 디스크 스토어는 별의미없습니다.

 

캐쉬가 저장되는 순서는 메모리> 빅메모리> 파일시스템입니다.

 

캐쉬를 사용했을때 장점

 

 

 

Speeding up CPU-bound Applications

Speeding up I/O-bound Applications

Increased Application Scalability

 

이렇게 세가지 장점이 있습니다. 물론 단점도 존재하죠~

 

 

Ehcache 특징은 다음과 같습니다

 

Features


Fast and Light Weight

Fast >빠르다 

Over the years, various performance tests have shown Ehcache to be one of the fastest Java caches.

> 수년에 걸쳐서 java 캐쉬중에 가장 빠른 성능을 보여줬다.

Ehcache's threading is designed for large, high concurrency systems.

>Ehcache의 쓰레딩은 크고 높은 동시성 시스템을 위해 설계 되었습니다.(아마도 거대한 시스템과 멀티스레드 환경을 지원한다는 뜻인거 같습니다)

Extensive performance tests in the test suite keep Ehcache's performance consistent between releases.

>광범위한 테스트로 릴리즈 마다 Ehcache의 성능을 유지하고 있습니다.

Simple> 간단하다

Many users of Ehcache hardly know they are using it.

>많은 사용자들이 Ehcache를 사용하고 있는지 잘 모른다.

Sensible defaults require no initial configuration.

>(대충 초기 구성이 쉽다는 뜻인거 같습니다)...

The API is very simple and easy to use, making it possible to get up and running in minutes.

>API는 매우 간단하게 사용 할수 있고, 몇분만에 돌아갈수 있게 할수 있다.

See the Code Samples for details.> 코드 샘플을 보아라~

Small foot print> 작은 용량

Ehcache 2.2.3 is 668 kb making it convenient to package.

>Ehcache는 668kb정도 됩니다.

Minimal dependencies> 적은 의존도

The only dependency for core use is SLF4J.

>SLF4J만 의존하고 있다.

(이정도면 굉장히 작은거죠? 의존도 작을수록 쓰기 편해요)


Scalable> 확장성

Provides Memory and Disk stores for scalability into gigabytes

>

The largest Ehcache installations use memory and disk stores in the gigabyte range.

Ehcache is tuned for these large sizes.

And with BigMemory, that can be taken up to hundreds of GB, all in process.

Scalable to hundreds of caches

The largest Ehcache installations use hundreds of caches.

Tuned for high concurrent load on large multi-CPU servers

There is a tension between thread safety and performance. Ehcache's threading started off coarse-grained, but has increasingly made use of ideas from Doug Lea to achieve greater performance. Over the years there have been a number of scalability bottlenecks identified and fixed.

Multiple CacheManagers per virtual machine

Ehcache 1.2 introduced multiple CacheManagers per virtual machine. This enables completely difference ehcache.xml configurations to be applied.

Scalable to hundreds of nodes with the Terracotta Server Array

By adding Terracotta, Ehcache can scale to any use case. See more details about Terracotta caching at Distributed Caching With Terracotta.


Flexible> 유연함

Supports Object or Serializable caching

As of ehcache-1.2 there is an API for Objects in addition to the one for Serializable. Non-serializable Objects can use all parts of Ehcache except for DiskStore and replication. If an attempt is made to persist or replicate them they are discarded and a WARNING level log message emitted.

The APIs are identical except for the return methods from Element. Two new methods on Element: getObjectValue and getKeyValue are the only API differences between the Serializable and Object APIs. This makes it very easy to start with caching Objects and then change your Objects to Seralizable to participate in the extra features when needed. Also a large number of Java classes are simply not Serializable.

Support cache-wide or Element-based expiry policies

Time to lives and time to idles are settable per cache. In addition, from ehcache-1.2.1, overrides to these can be set per Element.

Provides LRU, LFU and FIFO cache eviction policies

Ehcache 1.2 introduced Less Frequently Used and First In First Out caching eviction policies. These round out the eviction policies.

Provides Memory and Disk stores

Ehcache, like most of the cache solutions, provides high performance memory and disk stores.

Dynamic, Runtime Configuration of Caches

The time-to-live, time-to-idle, maximum in-memory and on-disk capacities can be tuned at runtime simply by mutating the cache's configuration object.


Standards Based> 표준 기반

Full implementation of JSR107 JCACHE API

Ehcache offers the the most complete implementation of the JSR107 JCACHE to date.

Because JCACHE has not yet been released the JCACHE API that Ehcache implements has been released as net.sf.jsr107cache.

Implementers can code to the JCACHE API which will create portability to other caching solutions in the future.

The maintainer of ehcache, Greg Luck, is on the expert committee for JSR107.


Extensible>확장

Listeners may be plugged in

Ehcache 1.2 provides CacheManagerEventListener and CacheEventListener interfaces. Implementations can be plugged in and configured in ehcache.xml.

Peer Discovery, Replicators and Listeners may be plugged in

Distributed caching, introduced in Ehcache 1.2 involves many choices and tradeoffs. The Ehcache team believe that one size will not fit all.

Implementers can use built-in mechanisms or write their own. A plugin development guide is included for this purpose.

Cache Extensions may be plugged in

Create your own Cache Extensions, which hold a reference to a cache and are bound to its lifecycle.

Cache Loaders may be plugged in

Create your own Cache Loaders, which are general purpose asynchronous methods for loading data into caches, or use them in pull-through configuration.

Cache Exception Handlers may be plugged in

Create an Exception Handler which is invoked if any Exception occurs on a cache operation.


Application Persistence>

Persistent disk store which stores data between VM restarts

With Ehcache 1.1 in 2004, Ehcache was the first open source Java cache to introduce persistent storage of cache data on disk on shutdown. The cached data is then accessible the next time the application runs.

Flush to disk on demand

With Ehcache 1.2, the flushing of entries to disk can be executed with a cache.flush() method whenever required, making it easier to use ehcache


Listeners> 리스너들

CacheManager listeners

Register Cache Manager listeners through the CacheManagerEventListener interface with the following event methods:

  • notifyCacheAdded()
  • notifyCacheRemoved()

Cache event listeners

Register Cache Event Listeners through the CacheEventListener interfaces, which provides a lot of flexibility for post-processing of cache events. The methods are:

  • notifyElementRemoved
  • notifyElementPut
  • notifyElementUpdated
  • notifyElementExpired

JMX Enabled> JMS 활성

Ehcache is JMX enabled. You can monitor and manage the following MBeans:

  • CacheManager
  • Cache
  • CacheConfiguration
  • CacheStatistics

See the net.sf.ehcache.management package.

See http://weblogs.java.net/blog/maxpoon/archive/2007/06/extending_the_n_2.html for an online tutorial.


Distributed Caching> 분산 캐쉬

Since Ehcache 1.2 full support has been available for high performance distributed caching that is flexible and extensible.

Included options for distributed caching are:

  • Clustered caching via Terracotta: two lines of configuration is all that is required to setup and use Ehcache with Terracotta. Cache discovery is automatic, and many options exist for tuning the cache behavior and performance for your use case.
  • Replicated caching via RMI, JGroups, or JMS: Cache discovery is implemented via multicast or manual configuration. Updates are delivered either asynchronously or synchronously via custom RMI connections.
  • Custom: a comprehensive plugin mechanism provides support for custom discovery and replication implementations. See the Distributed Caching documentation for more feature details.

Distributed Caching with Terracotta

Simple yet powerful clustered caching. Just two lines of configuration is all that is required. For more information see Distributed Caching With Terracotta.

Replicated Caching via RMI, JGroups, or JMS

No programming changes are required to make use of replication. Only configuration in ehcache.xml.

Available replication options are:

  • Ehcache 1.6+ supports replication via RMI, JGroups, and JMS
  • Synchronous or asynchronous replication, per cache, as appropriate.
  • Copy or invalidate, per cache, as appropriate.

Reliable Delivery

The built-in delivery mechanism uses RMI with custom sockets over TCP, not UDP.

Peer Discovery

Peer discovery may be either manually configured or automatic, using multicast. Multicast is simple, and adds and removes peers automatically. Manual configuration gives fine control and is useful for situations where multicast is blocked.

Extensible

Distributed caching, introduced in Ehcache 1.2 involves many choices and tradeoffs. The Ehcache team believe that one size will not fit all.

Implementers can use built-in mechanisms (such as Terracotta, RMI, Jgroups, or JMS) or write their own. A plugin development guide is included for this purpose.

Bootstrapping from Peers

Distributed caches enter and leave the cluster at different times. Caches can be configured to bootstrap themselves from the cluster when they are first initialized.

An abstract factory, BootstrapCacheLoaderFactory has been defined along with an interface BootstrapCacheLoader along with an RMI based default implementation.


Cache Server> 캐쉬 서버

Ehcache now comes with a Cache Server, available as a WAR for most web containers, or as a standalone server. The Cache Server has two apis: RESTful resource oriented, and SOAP. Both support clients in any programming language.

RESTful cache server

The Ehcache implementation strictly follows the RESTful resource-oriented architecture style.

Specifically:

  • The HTTP methods GET, HEAD, PUT/POST and DELETE are used to specify the method of the operation. The URI does not contain method information.
  • The scoping information, used to identify the resource to perform the method on, is contained in the URI path.
  • The RESTful Web Service is described by and exposes a WADL (Web Application Description Language) file. It contains the URIs you can call, and what data to pass and get back. Use the OPTIONS method to return the WADL.

For performance, HTTP/1.1 caching features are fully supported such as Last-Modified, ETag and so on. Ehcache responsds correctly to HEAD and conditional GET requests.

SOAP cache server

The Ehcache RESTFul Web Services API exposes the singleton CacheManager, which typically has been configured in ehcache.xml or an IoC container. Multiple CacheManagers are not supported.

The API definition is as follows:

Comes as a WAR or as a complete server

The standalone server comes with its own embedded Glassfish web container.

It also comes packaged as a WAR for deployment to any Servlet 2.5 web container. Glassfish V2/3, Tomcat 6 and Jetty 6 have been tested.


Standalone and distributed search using a fluent query language. See the search documentation


Java EE and Applied Caching >

High quality implementations for common caching scenarios and patterns.

Blocking Cache to avoid duplicate processing for concurrent operations

A cache which blocks subsequent threads until the first read thread populates a cache entry.

SelfPopulating Cache for pull through caching of expensive operations

SelfPopulatingCache - a read-through cache. A cache that populates elements as they are requested without requiring the caller to know how the entries are populated. It also enables refreshes of cache entries without blocking reads on the same entries.

Java EE Gzipping Servlet Filter

  • CachingFilter - an abstract, extensible caching filter.
  • SimplePageCachingFilter

    A high performance Java EE servlet filter that caches pages based on the request URI and Query String. It also gzips the pages and delivers them to browsers either gzipped or ungzipped depending on the HTTP request headers. Use to cache entire Servlet pages, whether from JSP, velocity, or any other rendering technology.

    Tested with Orion and Tomcat.

  • SimplePageFragmentCachingFilter

    A high performance Java EE filter that caches page fragments based on the request URI and Query String. Use with Servlet request dispatchers to cache parts of pages, whether from JSP, velocity, or any other rendering technology. Can be used from JSPs using jsp:include.

    Tested with Orion and Tomcat.

  • Works with Servlet 2.3 and Servlet 2.4 specifications.

Cacheable Commands

This is the trusty old command pattern with a twist: asynchronous behaviour, fault tolerance and caching. Creates a command, caches it and then attempts to execute it.

Works with Hibernate

Tested with Hibernate2.1.8 and Hibernate3.1.3, which can utilise all of the new features except for Object API and multiple session factories each using a different Ehcache CacheManager.

A new net.sf.ehcache.hibernate.EhCacheProvider makes those additional features available to Hibernate-3.1.3. A version of the new provider should make it into the Hibernate3.2 release.

Works with Google App Engine

Ehcache-1.6 is compatible with Google App Engine.

See the Google App Engine How-To.

Transactional support through JTA

Ehcache-2.0 has support for JTA, making it a fully XA compliant resource participating in the transaction, two-phase commit and recovery. Ehcache 2.3 added support for local transactons.

See the complete JTA documentation.


Open Source Licensing> 오픈 소스 라이센싱

Apache 2.0 license

Ehcache's original Apache1.1 copyright and licensing was reviewed and approved by the Apache Software Foundation, making Ehcache suitable for use in Apache projects. ehcache-1.2 is released under the updated Apache 2.0 license.

The Apache license is also friendly one, making it safe and easy to include Ehcache in other open source projects or commercial products.

 

혹 해석이 틀리면 써주세요 ㅠ_ㅠ

 

 

해석은 귀찬아서 패스 ..나중에 해드릴게요..


역시 영어를 잘해야 최신기술을 빨리 습득할수 있네요~