SpringFramework Cache(Javaアプリケーション)
今回はCacheをやります。DBアクセスなど処理に時間が掛かるメソッドなどに使用します。getメソッドでは1度アクセスさせた引数と戻り値をキャッシュに保持し、次にアクセスされたときに
メソッド内部の処理を行うのではなく、キャッシュ値を戻します。
setメソッドでは本来の更新処理に加えてキャッシュ値の更新を行います。
Springプロジェクトを作る手順は以前と同様ですが、設定ファイルの中身やソースを変えます。
pom.xml
変更なしです。Spring用の設定ファイル(SpringTest.xml)
スキーマ、スキーマロケーション、キャッシュのannotation-driven、cacheManager、キャッシュを行うクラスを追加します。ここではcacheManagerにSimpleCacheManagerを使用し、キャッシュを行うクラスにConcurrentMapCacheFactoryBeanを指定します。
キャッシュの名前は test にしています。
<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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd">
<bean id="helloWorld" class="spring.test.SpringBean">
</bean>
<cache:annotation-driven />
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean
class=
"org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean">
<property name="name" value="test" />
</bean>
</set>
</property>
</bean>
</beans>
HelloWorldTest.java
呼び出し元クラスは、何も意識しなくて良いです。
package spring.test;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class HelloWorldTest {
public static void main(String[] args) {
FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("C:\\workspace\\springApp\\SpringTest.xml");
// FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext("classpath:SpringTest.xml");
SpringBean bean = (SpringBean) context.getBean("helloWorld");
bean.setText("xx", "xxxx");
System.out.println(bean.getText("xx"));
System.out.println(bean.getText("xx"));
System.out.println(bean.getText("xx"));
bean.setText("xx", "xxxx");
System.out.println(bean.getText("xx"));
context.close();
}
}
SpringBean.java
キャッシュを利用するメソッドに@Cacheableを付け、キャッシュを更新するメソッドに@CacheEvictを付けます。アノテーションの引数にはキャッシュの名前とキャッシュのキーとなる変数(頭に#を付ける)を指定します。
package spring.test;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
public class SpringBean {
Map<String, String> map = new HashMap<>();
@Cacheable(value = "test", key = "#keyTxt")
public String getText(String keyTxt) {
System.out.println("getText");
return map.get(keyTxt);
}
@CacheEvict(value = "test", key = "#key")
public void setText(String key, String value) {
System.out.println("setText");
map.put(key, value);
}
}
キャッシュ関連のアノテーションはいくつかありますが、一部を紹介します。
アノテーション | 説明 |
---|---|
@Cacheable | キャッシュを使用する |
@CacheEvict | キャッシュをクリアする |
@CachePut | キャッシュを更新する |
実行イメージ
ちなみにキャッシュを利用しないと以下のようになります。
ページのトップへ戻る