In this article, I’ll record the development experience about how to use guava cache manager under spring framework, mainly about the common properties, main process and give a sample.
- Add schema in xml to let spring recognize cache tags.
xmlns:cache="http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"
- Enbale cache annotation and leave expansion room for configurations.
<context:annotation-config /> <cache:annotation-driven />
- Configure cache manager.
<bean id="cacheManager" class="org.springframework.cache.guava.GuavaCacheManager"> <property name="cacheBuilderSpec"> <bean class="com.google.common.cache.CacheBuilderSpec" factory-method="parse"> <constructor-arg name="cacheBuilderSpecification" value="expireAfterWrite=3600s" /> # calculate the effective time from the first arrival of the visit and do not redo caculation during the period 3600s. </bean> </property> </bean>
- Use cache manager.
@Cacheable(cacheNames = "receiveTicketInfo", cacheManager = "cacheManager", key = "#accessToken") public JSONObject receiveTicketInfo(String accessToken) { log.info("Trace: WechatShareServiceImpl.receiveTicketInfo(String accessToken)"); ... }
- Dependencies required.
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.guava/guava --> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency>
Refer to:
https://docs.spring.io/spring/docs/current/spring-framework-reference/html/cache.html