Spring EhCacheキャッシュのannotation注記

4260 ワード

1.pom.xmlにehcache依存パッケージを追加
                     net.sf.ehcache             ehcache             2.9.1         
2.classpathでehcacheプロファイルehcacheを追加する.xml


    

    

   


3.springプロファイルアプリケーションContext.xml赤斜体部分構成の追加に注意
 xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.2.xsd" >
4.サービス層に注記構成を追加
4.1 Using Spring 3.1 spring 3.1以降の構成
@Cacheable
Cache a method call. In the following example, the value is the return type, a Manual. The key is extracted from the ISBN argument using the id.
@org.springframework.cache.annotation.Cacheable(value="QY_api_productTop",
 key="#isbn.id") 
public Manual findManual(ISBN isbn, boolean checkWarehouse)

key=「#isbn.id」オブジェクトキャッシュのkey値は、唯一であることを保証する必要があります.SpringのSpEL式を使用し、isbnオブジェクトのid属性値を取得します.
value="QY_api_productTop":ehcache.xmlのキャッシュ名
属性id<10を含む条件conditionもサポートされています.以下のようにします.
@Cacheable(value = "QY_api_productTop",key="#isbn.id",condition = "#isbn.id<10")
public Manual findManual(ISBN isbn, boolean checkWarehouse)

  
@CacheEvict 
Clears the cache when called.クリアQY_api_ProductTopキャッシュ内のすべてのオブジェクト
@org.springframework.cache.annotation.CacheEvict(value = "QY_api_productTop",
 allEntries=true) 
public void loadManuals(Long id)

指定したオブジェクトのキャッシュをクリアするには、次のようにします.
@CacheEvict(value = "QY_api_productTop", key = "#id")
public void loadManuals(Long id)

4.2 Spring 2.5 to 3.1バージョン構成は以下のjarにも依存する
  
    com.googlecode.ehcache-spring-annotationsgroupId>  
    ehcache-spring-annotationsartifactId>  
    1.1.2version>  
    jartype>  
    compilescope>  
dependency> 
This open source, led by Eric Dalquist, predates the Spring 3.1 project. You can use it with earlier versions of Spring, or you can use it with 3.1.
@Cacheable
As with Spring 3.1 it uses an @Cacheable annotation to cache a method. In this example calls to findMessage are stored in a cache named “messageCache”. The values are of type Message. The id for each entry is the id argument given.
@Cacheable(cacheName = "messageCache") public Message findMessage(long id)
@TriggersRemove
And for cache invalidation, there is the @TriggersRemove annotation. In this example, cache.removeAll() is called after the method is invoked.
@TriggersRemove(cacheName = "messagesCache", when = When.AFTER_METHOD_INVOCATION, removeAll = true) public void addMessage(Message message)
5.テスト検証、印刷されたsqlの表示
例えばhibernate構成でshow_を設定するsql=true
true

5.1キャッシュメソッドに最初にアクセスした後、キャッシュ時間内に複数のアクセスでsql出力があるかどうかを確認し、キャッシュに正常ではない
5.2 2回目の出力時間と1回目の時間間隔はehcacheより大きいかどうか.xmlで設定された時間はキャッシュに通常より大きい