1.2. 使用 Data Grid 作为 Spring Cache 供应商
将 @EnableCaching 注释添加到您的其中一个配置类,然后添加 @Cacheable 和 @CacheEvict 注释以使用远程或嵌入式缓存。
先决条件
- 将 Data Grid 依赖项添加到应用程序项目中。
- 如果您使用 Data Grid Server 部署,请创建所需的远程缓存并配置 Hot Rod 客户端属性。
流程
使用以下方法之一在应用程序上下文中启用缓存注解:
声明
<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" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <cache:annotation-driven /> </beans>programmatic
@EnableCaching @Configuration public class Config { }使用
@Cacheable注解方法来缓存返回值。提示要直接引用缓存中的条目,您必须包含
key属性。-
使用
@CacheEvict注解方法,以从缓存中删除旧条目。