© 2010-2019 原始作者。
| 您可以为自己的使用目的复制本文档,并分发给他人,前提是您不为此类副本收取任何费用,并且无论以印刷版还是电子版形式分发,每个副本都包含此版权声明。 |
前言
Pivotal GemFire 的 Spring Data 专注于将 Spring 框架强大的非侵入式编程模型和概念与 Pivotal GemFire 集成,以在使用 Pivotal GemFire 作为数据管理解决方案时,简化 Java 应用程序的配置和开发。
本文档假设您已经对核心 Spring 框架和 Pivotal GemFire 概念有基本的了解和熟悉。
尽管我们已尽一切努力确保本文档内容全面、完整且没有错误,但有些主题超出了本文档的范围,可能需要更多解释(例如,使用 HA 的分区进行数据分发管理,同时仍保持一致性)。此外,可能存在一些排版错误。如果您发现错误,甚至是更严重的错误,请通过在 JIRA 中提出适当的 问题,提请 Spring Data 团队注意这些问题。
1. 简介
Pivotal GemFire 的 Spring Data 参考指南解释了如何使用 Spring 框架配置和开发使用 Pivotal GemFire 的应用程序。它介绍了基本概念并提供了大量示例,以帮助您快速入门。
2. 要求
Pivotal GemFire 的 Spring Data 需要 Java 8.0、Spring Framework 5 和 Pivotal GemFire 9.8.2。
3. 新功能
| 从 1.2.0.RELEASE 开始,该项目(以前称为 Spring GemFire)已更名为 Pivotal GemFire 的 Spring Data,以反映它现在是 Spring Data 项目的一个模块,并构建在 Pivotal GemFire 之上。 |
3.1. 1.2 版本中的新功能
-
通过 SDG
gfeXML 命名空间全面支持 Pivotal GemFire 配置。现在,Pivotal GemFire 组件可以完全配置,而无需本地cache.xml文件。 -
Pivotal GemFire 6.6.x 的 WAN 网关支持。请参阅 配置 WAN 网关
-
使用专用 SDG XML 命名空间 gfe-data 的 Spring Data 存储库支持。请参阅 Pivotal GemFire 的 Spring Data 存储库
-
gfe-dataXML 命名空间支持注册 Pivotal GemFire 函数。请参阅 配置函数服务 -
顶级
<disk-store>元素已添加到 SDGgfeXML 命名空间,以允许在区域以及支持持久备份或溢出的其他 Pivotal GemFire 组件之间共享持久存储。请参阅 [bootstrap-diskstore]<*-region>元素不再允许嵌套<disk-store>元素。 -
Pivotal GemFire 子区域由嵌套的
<*-region>元素支持。 -
已添加
<local-region>元素以配置本地区域。 -
支持 Pivotal GemFire 7.0 中重新设计的 WAN 网关。
3.2. 1.3 版本中的新功能
-
升级到 Spring Framework 3.2.8。
-
升级到 Spring Data Commons 1.7.1。
-
Pivotal GemFire 函数的注解支持。现在可以使用注解声明和注册作为 POJO 编写的函数。此外,函数执行被定义为带注解的接口,类似于 Spring Data 存储库的工作方式。请参阅 函数执行的注解支持。
-
向 SDG XML 命名空间添加了
<datasource>元素,以简化建立与 Pivotal GemFire 数据网格的基本客户端连接。 -
向 SDG
gfe-dataXML 命名空间添加了<json-region-autoproxy>元素,以支持 Pivotal GemFire 7.0 中引入的 JSON 功能,从而使 Spring AOP 能够在区域数据访问操作上自动执行必要的转换。 -
升级到 Pivotal GemFire 7.0.1 并添加了新
AsyncEventQueue属性的 XML 命名空间支持。 -
添加了对设置区域订阅兴趣策略的支持。
-
支持函数执行的 void 返回。有关完整详细信息,请参阅 函数执行的注解支持。
-
支持持久化本地区域。请参阅 本地区域。
-
支持 Pivotal GemFire 客户端缓存上的条目存活时间 (TTL) 和条目空闲时间 (TTI)。请参阅 配置 Pivotal GemFire ClientCache
-
支持通过使用单个 Pivotal GemFire 集群同时在 tc Server 内部运行多个 Pivotal GemFire 的 Spring Data Web 应用程序。
-
通过使用 SDG
gfeXML 命名空间,支持所有缓存区域定义上的concurrency-checks-enabled。请参阅 [bootstrap:region:common:attributes] -
支持客户端本地区域上的
CacheLoaders和CacheWriters。 -
支持在 Pivotal GemFire 缓存子区域上注册
CacheListeners、AsyncEventQueues和GatewaySenders。 -
支持区域中的 PDX 持久键。
-
支持在 Spring 上下文中正确创建分区区域 bean,当使用
colocated-with属性指定并置时。 -
通过在 SDG
gfeXML 命名空间中使用适当的嵌套<*-region>元素语法,全面支持缓存子区域。
3.3. 1.4 版本中的新功能
-
升级到 Pivotal GemFire 7.0.2。
-
升级到 Spring Framework 3.2.13.RELEASE。
-
升级到 Spring Data Commons 1.8.6.RELEASE。
-
将 Pivotal GemFire 的 Spring Data 与 Spring Boot 集成,其中包括
spring-boot-starter-data-gemfirePOM 和一个 Spring Boot 示例应用程序,该应用程序演示了使用 SDG 配置并使用 Spring Boot 引导的 Pivotal GemFire 缓存事务。 -
添加了对从
Gfsh启动时在 Pivotal GemFire 服务器中引导 SpringApplicationContext的支持。请参阅 在 Pivotal GemFire 中引导 Spring ApplicationContext -
添加了对将应用程序域对象和实体持久化到多个 Pivotal GemFire 缓存区域的支持。请参阅 实体映射
-
添加了对将应用程序域对象和实体持久化到 Pivotal GemFire 缓存子区域的支持,从而在子区域可唯一识别但名称相同时避免冲突。请参阅 实体映射
-
向所有 Pivotal GemFire 缓存区域类型的数据策略和区域快捷方式添加了严格的 XSD 类型规则。
-
将 SDG
<*-region>元素的默认行为从查找更改为始终创建一个新区域,并可以选择使用ignore-if-exists属性恢复旧行为。请参阅 常见区域属性 和 [bootstrap:region:common:regions-subregions-lookups-caution] -
Pivotal GemFire 的 Spring Data 现在可以完全在 JDK 7 和 JDK 8 上构建和运行。
3.4. 1.5 版本中的新功能
-
保持与 Pivotal GemFire 7.0.2 的兼容性。
-
升级到 Spring Framework 4.0.9.RELEASE。
-
升级到 Spring Data Commons 1.9.4.RELEASE。
-
将参考指南转换为 Asciidoc。
-
重新支持在 OSGi 容器中部署 Pivotal GemFire 的 Spring Data。
-
删除了 Pivotal GemFire XML 命名空间区域类型元素中指定的所有默认值,转而依赖 Pivotal GemFire 默认值。
-
增加了自动创建
DiskStore目录位置的便利性。 -
SDG 注解的函数实现现在可以从
Gfsh执行。 -
启用了 Pivotal GemFire
GatewayReceivers的手动启动。 -
添加了对自动区域查找的支持。请参阅 [bootstrap:region:auto-lookup]
-
添加了对区域模板的支持。请参阅 [bootstrap:region:common:region-templates]
3.5. 1.6 版本中的新功能
-
升级到 Pivotal GemFire 8.0.0。
-
保持与 Spring Framework 4.0.9.RELEASE 的兼容性。
-
升级到 Spring Data Commons 1.10.2.RELEASE。
-
添加了对 Pivotal GemFire 8 新的基于集群的配置服务的支持。
-
启用了“自动重新连接”功能,可在 Spring 配置的 Pivotal GemFire 服务器中使用。
-
允许创建并发和并行
AsyncEventQueues和GatewaySenders。 -
添加了对 Pivotal GemFire 8 区域数据压缩的支持。
-
添加了用于设置
DiskStore使用临界百分比和警告百分比的属性。 -
支持向
GatewaySenders添加EventSubstitutionFilters的功能。
3.6. 1.7 版本中的新功能
-
升级到 Pivotal GemFire 8.1.0。
-
升级到 Spring Framework 4.1.9.RELEASE。
-
升级到 Spring Data Commons 1.11.6.RELEASE。
-
添加了对 Apache Geode 的早期访问支持。
-
添加了对在 Spring XML、
cache.xml甚至 Pivotal GemFire 的集群配置服务中配置的现有区域上添加 Spring 定义的CacheListeners、CacheLoaders和CacheWriters的支持。 -
为
SpringContextBootstrappingInitializer添加了 Spring JavaConfig 支持。 -
添加了对
SpringContextBootstrappingInitializer中自定义ClassLoaders的支持,以加载 Spring 定义的 bean 类。 -
添加了对
LazyWiringDeclarableSupport重新初始化和WiringDeclarableSupport完整替换的支持。 -
向
<gfe:pool>元素添加了locators和servers属性,允许使用 Spring 的属性占位符配置可变定位器和服务器端点列表。 -
启用了
<gfe-data:datasource>元素与非 Spring 配置的 Pivotal GemFire 服务器的使用。 -
添加了多索引定义和创建支持。
-
添加了对缓存和区域数据快照的支持。请参阅 配置快照服务
3.7. 1.8 版本中的新功能
-
升级到 Pivotal GemFire 8.2.0。
-
升级到 Spring Framework 4.2.9.RELEASE。
-
升级到 Spring Data Commons 1.12.11.RELEASE。
-
添加了 Maven POM 以使用 Maven 构建 SDG。
-
添加了对 CDI 的支持。
-
启用了
ClientCache在没有Pool的情况下进行配置。 -
将
<gfe:cache>和<gfe:client-cache>元素的use-bean-factory-locator属性默认为 false。 -
向
<gfe:client-cache>添加了durable-client-id和durable-client-timeout属性。 -
使
GemfirePersistentProperty现在能够正确处理其他非实体、类似标量类型(例如BigDecimal和BigInteger)。 -
防止 SDG 定义的
Pools在使用这些Pools的Regions之前被销毁。 -
处理定义为存储库查询方法的 Pivotal GemFire OQL 查询不区分大小写的情况。
-
在 SDG 的 Spring 缓存抽象支持中,将
GemFireCache.evict(key)更改为调用Region.remove(key)。 -
修复了在与为 Pivotal GemFire 服务器组配置的特定
Pool关联的客户端Region上进行存储库查询时出现的RegionNotFoundException。 -
更改了
GatewaySenders/Receivers,使其不再绑定到 Spring 容器。
3.8. 1.9 版本中的新功能
-
升级到 Pivotal GemFire 8.2.11。
-
升级到 Spring Framework 4.3.18.RELEASE。
-
升级到 Spring Data Commons 1.13.13.RELEASE。
-
引入了受 Spring Boot 启发的全新基于注解的配置模型。
-
添加了对
GemfireTransactionManager中暂停和恢复的支持。 -
在存储库中添加了对使用 bean
id属性作为区域键的支持,当不存在@Id注解时。 -
在使用
@EnablePdx时,将MappingPdxSerializer用作默认的 Pivotal GemFire 序列化策略。 -
使
GemfireCacheManager能够明确列出要在 Spring Caching Abstraction 中使用的区域名称。 -
配置了 Pivotal GemFire 缓存、缓存服务器、定位器、池、区域、索引、磁盘存储、过期、淘汰、统计信息、多播、HttpService、Auth、SSL、日志记录、系统属性。
-
添加了对类路径上多个 Spring Data 模块的存储库支持。
3.9. 2.0 版本中的新功能
-
升级到 Pivotal GemFire 9.1.1。
-
升级到 Spring Data Commons 2.0.8.RELEASE。
-
升级到 Spring Framework 5.0.7.RELEASE。
-
通过按关注点打包不同的类和组件来重组 SDG 代码库。
-
为 Java 8 类型添加了广泛的支持,尤其是在 SD Repository 抽象中。
-
更改了 Repository 接口和抽象,例如,ID 不再需要是
java.io.Serializable。 -
默认情况下,将
@EnableEntityDefinedRegions注解的ignoreIfExists属性设置为true。 -
默认情况下,将
@Indexed注解的override属性设置为false。 -
将
@EnableIndexes重命名为@EnableIndexing。 -
引入了
InterestsBuilder类,以便在使用 JavaConfig 时轻松方便地表达客户端和服务器之间的键和值兴趣。 -
在注解配置模型中添加了对堆外内存、Redis 适配器和 Pivotal GemFire 新安全框架的支持。
参考指南
4. 文档结构
以下章节解释了 Pivotal GemFire 的 Spring Data 提供的核心功能
-
使用 Spring 容器引导 Pivotal GemFire 描述了为配置、初始化和访问 Pivotal GemFire 缓存、区域和相关分布式系统组件提供的配置支持。
-
使用 Pivotal GemFire API 解释了 Pivotal GemFire API 与 Spring 中可用的各种数据访问功能(例如基于模板的数据访问、异常转换、事务管理和缓存)之间的集成。
-
使用 Pivotal GemFire 序列化 描述了对 Pivotal GemFire 管理对象的序列化和反序列化的增强。
-
POJO 映射 描述了使用 Spring Data 存储在 Pivotal GemFire 中的 POJO 的持久化映射。
-
Pivotal GemFire 的 Spring Data 存储库 描述了如何创建和使用 Spring Data 存储库,通过基本的 CRUD 和简单的查询操作访问存储在 Pivotal GemFire 中的数据。
-
函数执行的注解支持 描述了如何使用注解创建和使用 Pivotal GemFire 函数,以在数据所在地执行分布式计算。
-
连续查询 (CQ) 描述了如何使用 Pivotal GemFire 的连续查询 (CQ) 功能,根据通过 Pivotal GemFire 的 OQL(对象查询语言)定义和注册的兴趣来处理事件流。
-
在 Pivotal GemFire 中引导 Spring ApplicationContext 描述了如何使用
Gfsh配置和引导在 Pivotal GemFire 服务器中运行的 SpringApplicationContext。 -
示例应用程序 描述了发行版中提供的示例,以说明 Pivotal GemFire 的 Spring Data 中可用的各种功能。
5. 使用 Spring 容器引导 Pivotal GemFire
Pivotal GemFire 的 Spring Data 提供使用 Spring IoC 容器对 Pivotal GemFire 内存数据网格 (IMDG) 的全面配置和初始化。该框架包含几个类,有助于简化 Pivotal GemFire 组件的配置,包括:缓存、区域、索引、磁盘存储、函数、WAN 网关、持久性备份以及其他几个分布式系统组件,以最少的努力支持各种应用程序用例。
| 本节假设您对 Pivotal GemFire 有基本的了解。有关更多信息,请参阅 Pivotal GemFire 产品文档。 |
5.1. 使用 Spring 优于 Pivotal GemFire cache.xml 的优点
Pivotal GemFire 的 Spring Data 的 XML 命名空间支持对 Pivotal GemFire 内存数据网格 (IMDG) 的完全配置。XML 命名空间是在 Spring 上下文中配置 Pivotal GemFire 的两种方法之一,以便在 Spring 容器中正确管理 Pivotal GemFire 的生命周期。在 Spring 上下文中配置 Pivotal GemFire 的另一种方法是使用基于注解的配置。
虽然对 Pivotal GemFire 的本机 cache.xml 的支持出于历史原因仍然存在,但鼓励使用 XML 配置的 Pivotal GemFire 应用程序开发人员在 Spring XML 中完成所有工作,以利用 Spring 提供的许多出色功能,例如模块化 XML 配置、属性占位符和覆盖、SpEL (Spring 表达式语言) 和环境配置文件。在 XML 命名空间背后,Pivotal GemFire 的 Spring Data 广泛使用 Spring 的 FactoryBean 模式来简化 Pivotal GemFire 组件的创建、配置和初始化。
Pivotal GemFire 提供了几个回调接口,例如 CacheListener、CacheLoader 和 CacheWriter,允许开发人员添加自定义事件处理程序。使用 Spring 的 IoC 容器,您可以将这些回调配置为普通的 Spring bean 并将其注入 Pivotal GemFire 组件。这是对本机 cache.xml 的重大改进,后者提供的配置选项相对有限,并且要求回调实现 Pivotal GemFire 的 Declarable 接口(请参阅 连线 Declarable 组件 以了解如何在 Spring 容器中仍然使用 Declarables)。
此外,IDE(例如 Spring Tool Suite (STS))为 Spring XML 命名空间提供了出色的支持,包括代码补全、弹出注解和实时验证。
5.2. 使用核心命名空间
为了简化配置,Pivotal GemFire 的 Spring Data 为配置核心 Pivotal GemFire 组件提供了专用的 XML 命名空间。可以使用 Spring 的标准 <bean> 定义直接配置 bean。但是,所有 bean 属性都通过 XML 命名空间公开,因此使用原始 bean 定义几乎没有好处。
| 有关 Spring 中基于 XML Schema 的配置的更多信息,请参阅 Spring 框架参考文档中的附录。 |
| Spring Data Repository 支持使用单独的 XML 命名空间。有关如何配置 Pivotal GemFire 的 Spring Data Repositories 的更多信息,请参阅 Pivotal GemFire 的 Spring Data 存储库。 |
要使用 Pivotal GemFire 的 Spring Data XML 命名空间,请在 Spring XML 配置元数据中声明它,如以下示例所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe="https://www.springframework.org/schema/gemfire" (1)(2)
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd (3)
">
<bean id ... >
<gfe:cache ...> (4)
</beans>
| 1 | Pivotal GemFire 的 Spring Data XML 命名空间前缀。任何名称都可以,但在本文档中,使用 gfe。 |
| 2 | XML 命名空间前缀映射到 URI。 |
| 3 | XML 命名空间 URI 位置。请注意,即使位置指向外部地址(它确实存在且有效),Spring 也会在本地解析模式,因为它包含在 Pivotal GemFire 的 Spring Data 库中。 |
| 4 | 使用 gfe 前缀的 XML 命名空间声明示例。 |
|
您可以将默认命名空间从
|
5.3. 使用数据访问命名空间
除了核心 XML 命名空间(gfe)之外,Pivotal GemFire 的 Spring Data 还提供了一个数据访问 XML 命名空间(gfe-data),其主要目的是简化 Pivotal GemFire 客户端应用程序的开发。此命名空间目前包含对 Pivotal GemFire 存储库 和函数执行的支持,以及一个 <datasource> 标签,它提供了一种便捷的方式来连接 Pivotal GemFire 集群。
5.3.1. 连接到 Pivotal GemFire 的简便方法
对于许多应用程序,使用默认值连接到 Pivotal GemFire 数据网格就足够了。Pivotal GemFire 的 Spring Data 的 <datasource> 标签提供了一种简单的数据访问方式。数据源会创建一个 ClientCache 和连接 Pool。此外,它会查询集群服务器以获取所有现有的根区域,并为每个区域创建一个(空的)客户端区域代理。
<gfe-data:datasource>
<locator host="remotehost" port="1234"/>
</gfe-data:datasource>
<datasource> 标签在语法上类似于 <gfe:pool>。它可以配置一个或多个嵌套的 locator 或 server 元素以连接到现有数据网格。此外,所有可用于配置池的属性都受支持。此配置会自动为连接到定位器的集群成员上定义的每个区域创建客户端区域 bean,因此它们可以被 Spring Data 映射注解 (GemfireTemplate) 无缝引用并自动装配到应用程序类中。
当然,您可以显式配置客户端区域。例如,如果您想将数据缓存到本地内存中,如以下示例所示
<gfe-data:datasource>
<locator host="remotehost" port="1234"/>
</gfe-data:datasource>
<gfe:client-region id="Example" shortcut="CACHING_PROXY"/>
5.4. 配置缓存
要使用 Pivotal GemFire,您需要创建新的缓存或连接到现有缓存。在当前版本的 Pivotal GemFire 中,每个 VM(更严格地说,每个 ClassLoader)只能有一个打开的缓存。在大多数情况下,缓存只应创建一次。
本节描述了对等 Cache 成员的创建和配置,适用于对等 (P2P) 拓扑和缓存服务器。Cache 成员也可以用于独立应用程序和集成测试。但是,在典型的生产系统中,大多数应用程序进程充当缓存客户端,而是创建 ClientCache 实例。这在配置 Pivotal GemFire ClientCache 和 客户端区域 部分中进行了描述。 |
可以使用以下简单声明创建一个具有默认配置的对等 Cache
<gfe:cache/>
在 Spring 容器初始化期间,任何包含此缓存定义的 ApplicationContext 都会注册一个 CacheFactoryBean,该工厂 bean 创建一个名为 gemfireCache 的 Spring bean,它引用一个 Pivotal GemFire Cache 实例。此 bean 引用现有 Cache,或者,如果不存在,则引用新创建的 Cache。由于未指定其他属性,新创建的 Cache 将应用默认缓存配置。
所有依赖于 Cache 的 Pivotal GemFire 的 Spring Data 组件都遵循此命名约定,因此您无需显式声明 Cache 依赖。如果您愿意,可以使用各种 SDG XML 命名空间元素提供的 cache-ref 属性使依赖显式,如下所示
<gfe:cache id="myCache"/>
Pivotal GemFire Cache 可以使用 Spring 完全配置。但是,Pivotal GemFire 的本机 XML 配置文件 cache.xml 也受支持。对于需要本机配置 Pivotal GemFire 缓存的情况,您可以使用 cache-xml-location 属性提供对 Pivotal GemFire XML 配置文件的引用,如下所示
<gfe:cache id="cacheConfiguredWithNativeCacheXml" cache-xml-location="classpath:cache.xml"/>
在此示例中,如果需要创建缓存,它将使用位于类路径根目录中名为 cache.xml 的文件进行配置。
该配置利用 Spring 的 Resource 抽象来查找文件。Resource 抽象允许根据运行时环境或资源位置中指定的前缀(如果有)使用各种搜索模式。 |
除了引用外部 XML 配置文件之外,您还可以指定使用 Spring 的任何 Properties 支持功能的 Pivotal GemFire 系统属性。
例如,您可以使用 util 命名空间中定义的 properties 元素直接定义 Properties,或从属性文件加载属性,如下所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
http://www.springframework.org/schema/util https://www.springframework.org/schema/util/spring-util.xsd
">
<util:properties id="gemfireProperties" location="file:/path/to/gemfire.properties"/>
<gfe:cache properties-ref="gemfireProperties"/>
</beans>
建议使用属性文件将特定于环境的设置外部化到应用程序配置之外。
| 缓存设置仅在需要创建新缓存时应用。如果 VM 中已存在打开的缓存,则这些设置将被忽略。 |
5.4.1. 高级缓存配置
对于高级缓存配置,cache 元素提供了许多配置选项,这些选项作为属性或子元素公开,如以下列表所示
(1)
<gfe:cache
cache-xml-location=".."
properties-ref=".."
close="false"
copy-on-read="true"
critical-heap-percentage="90"
eviction-heap-percentage="70"
enable-auto-reconnect="false" (2)
lock-lease="120"
lock-timeout="60"
message-sync-interval="1"
pdx-serializer-ref="myPdxSerializer"
pdx-persistent="true"
pdx-disk-store="diskStore"
pdx-read-serialized="false"
pdx-ignore-unread-fields="true"
search-timeout="300"
use-bean-factory-locator="true" (3)
use-cluster-configuration="false" (4)
>
<gfe:transaction-listener ref="myTransactionListener"/> (5)
<gfe:transaction-writer> (6)
<bean class="org.example.app.gemfire.transaction.TransactionWriter"/>
</gfe:transaction-writer>
<gfe:gateway-conflict-resolver ref="myGatewayConflictResolver"/> (7)
<gfe:dynamic-region-factory/> (8)
<gfe:jndi-binding jndi-name="myDataSource" type="ManagedDataSource"/> (9)
</gfe:cache>
| 1 | 属性支持各种缓存选项。有关此示例中所示的任何内容的更多信息,请参阅 Pivotal GemFire 产品文档。close 属性确定在关闭 Spring 应用程序上下文时是否应关闭缓存。默认值为 true。但是,对于多个应用程序上下文使用缓存的用例(在 Web 应用程序中很常见),请将此值设置为 false。 |
| 2 | 将 enable-auto-reconnect 属性设置为 true(默认值为 false)允许断开连接的 Pivotal GemFire 成员自动重新连接并重新加入 Pivotal GemFire 集群。有关更多详细信息,请参阅 Pivotal GemFire 产品文档。 |
| 3 | 将 use-bean-factory-locator 属性设置为 true(默认为 false)仅适用于同时使用 Spring (XML) 配置元数据和 Pivotal GemFire cache.xml 来配置 Pivotal GemFire 缓存节点(无论是客户端还是对等)的情况。此选项允许在 cache.xml 中表示的 Pivotal GemFire 组件(例如 CacheLoader)与 Spring 应用程序上下文中定义的 bean(例如 DataSource)自动装配。此选项通常与 cache-xml-location 结合使用。 |
| 4 | 将 use-cluster-configuration 属性设置为 true(默认值为 false)使 Pivotal GemFire 成员能够从定位器检索常见的共享集群配置。有关更多详细信息,请参阅 Pivotal GemFire 产品文档。 |
| 5 | 使用 bean 引用的 TransactionListener 回调声明示例。引用的 bean 必须实现 TransactionListener。可以实现 TransactionListener 来处理与事务相关的事件(例如 afterCommit 和 afterRollback)。 |
| 6 | 使用内部 bean 声明的 TransactionWriter 回调声明示例。该 bean 必须实现 TransactionWriter。TransactionWriter 是一个可以否决事务的回调。 |
| 7 | 使用 bean 引用的 GatewayConflictResolver 回调声明示例。引用的 bean 必须实现 https://gemfire-98-javadocs.docs.pivotal.io//org/apache/geode/cache/util/GatewayConflictResolver.html [GatewayConflictResolver]。GatewayConflictResolver 是一个缓存级插件,用于决定如何处理源自其他系统并通过 WAN 网关到达的事件。 |
| 8 | 启用 Pivotal GemFire 的 DynamicRegionFactory,它提供了一个分布式区域创建服务。 |
| 9 | 声明 JNDI 绑定以在 Pivotal GemFire 事务中注册外部 DataSource。 |
启用 PDX 序列化
前面的示例包含许多与 Pivotal GemFire 增强型序列化框架 PDX 相关的属性。虽然对 PDX 的完整讨论超出了本参考指南的范围,但重要的是要注意,PDX 是通过注册 PdxSerializer 来启用的,该序列化器通过设置 pdx-serializer 属性来指定。
Pivotal GemFire 提供了一个实现类 (org.apache.geode.pdx.ReflectionBasedAutoSerializer),它使用 Java 反射。但是,开发人员提供自己的实现是很常见的。属性的值只是对实现 PdxSerializer 接口的 Spring bean 的引用。
有关序列化支持的更多信息,请参阅使用 Pivotal GemFire 序列化。
启用自动重新连接
设置 <gfe:cache enable-auto-reconnect="[true|false*]> 属性为 true 时应小心。
通常,只有在使用 Pivotal GemFire 的 Spring Data XML 命名空间来配置和引导添加到集群的新非应用程序 Pivotal GemFire 服务器时才应启用“自动重新连接”。换句话说,当使用 Pivotal GemFire 的 Spring Data 开发和构建恰好是 Pivotal GemFire 集群的对等 Cache 成员的 Pivotal GemFire 应用程序时不应启用“自动重新连接”。
此限制的主要原因是,大多数 Pivotal GemFire 应用程序使用对 Pivotal GemFire Cache 或区域的引用来执行数据访问操作。这些引用由 Spring 容器“注入”到应用程序组件(例如存储库)中,供应用程序使用。当一个对等成员被强制断开与集群其余部分的连接时,可能是因为对等成员变得无响应或网络分区将一个或多个对等成员分隔成一个太小而无法作为独立分布式系统运行的组,对等成员会关闭,并且所有 Pivotal GemFire 组件引用(缓存、区域等)都将失效。
本质上,每个对等成员中当前的强制断开连接处理逻辑从头开始拆卸系统。JGroups 堆栈关闭,分布式系统进入关闭状态,最后缓存关闭。实际上,所有内存引用都变得陈旧并丢失。
与分布式系统断开连接后,对等成员进入“重新连接”状态并定期尝试重新加入分布式系统。如果对等成员成功重新连接,则成员会从现有成员重建其分布式系统的“视图”并接收新的分布式系统 ID。此外,所有缓存、区域和其他 Pivotal GemFire 组件都会重新构建。因此,所有旧的引用(可能已由 Spring 容器注入到应用程序中)现在都已陈旧且不再有效。
Pivotal GemFire 不保证(即使使用 Pivotal GemFire 公共 Java API)应用程序缓存、区域或其他组件引用会自动由重新连接操作刷新。因此,Pivotal GemFire 应用程序必须注意刷新自己的引用。
不幸的是,也没有办法收到断开连接事件的通知,随后也无法收到重新连接事件的通知。如果是那样,您将有一个清晰的方法来知道何时调用 ConfigurableApplicationContext.refresh()(如果它甚至适用于应用程序),这就是为什么不建议对对等 Cache 应用程序使用 Pivotal GemFire 的这个“功能”的原因。
有关“自动重新连接”的更多信息,请参阅 Pivotal GemFire 的 产品文档。
使用基于集群的配置
Pivotal GemFire 的集群配置服务是集群中任何对等成员加入时获取集群“一致视图”的便捷方式,它使用由定位器维护的共享持久化配置。使用基于集群的配置可确保对等成员的配置在成员加入时与 Pivotal GemFire 分布式系统兼容。
Pivotal GemFire 的 Spring Data 的此功能(将 use-cluster-configuration 属性设置为 true)的工作方式与 cache-xml-location 属性相同,只是 Pivotal GemFire 配置元数据的来源是通过定位器从网络获取,而不是本地文件系统中的本机 cache.xml 文件。
所有 Pivotal GemFire 本机配置元数据(无论是来自 cache.xml 还是来自集群配置服务)都会在任何 Spring (XML) 配置元数据之前应用。因此,Spring 的配置旨在“增强”本机 Pivotal GemFire 配置元数据,并且很可能特定于应用程序。
同样,要启用此功能,请在 Spring XML 配置中指定以下内容
<gfe:cache use-cluster-configuration="true"/>
虽然某些 Pivotal GemFire 工具(例如 Gfsh)会在发生类似模式的更改时“记录”其操作(例如,gfsh>create region --name=Example --type=PARTITION),但 Pivotal GemFire 的 Spring Data 的配置元数据不会被记录。直接使用 Pivotal GemFire 的公共 Java API 时也是如此。它也不会被记录。 |
有关 Pivotal GemFire 集群配置服务的更多信息,请参阅产品文档。
5.4.2. 配置 Pivotal GemFire CacheServer
Pivotal GemFire 的 Spring Data 包含对配置 CacheServer 的专用支持,允许通过 Spring 容器进行完整配置,如以下示例所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
">
<gfe:cache/>
<!-- Example depicting serveral Pivotal GemFire CacheServer configuration options -->
<gfe:cache-server id="advanced-config" auto-startup="true"
bind-address="localhost" host-name-for-clients="localhost" port="${gemfire.cache.server.port}"
load-poll-interval="2000" max-connections="22" max-message-count="1000" max-threads="16"
max-time-between-pings="30000" groups="test-server">
<gfe:subscription-config eviction-type="ENTRY" capacity="1000" disk-store="file://${java.io.tmpdir}"/>
</gfe:cache-server>
<context:property-placeholder location="classpath:cache-server.properties"/>
</beans>
前面的配置显示了 cache-server 元素和许多可用选项。
该配置不硬编码端口,而是使用 Spring 的 上下文 命名空间来声明 property-placeholder。一个 属性占位符 读取一个或多个属性文件,然后在运行时用值替换属性占位符。这样做允许管理员更改值而无需修改主应用程序配置。Spring 还提供了 SpEL 和一个 环境抽象,以支持将特定于环境的属性从主代码库外部化,从而简化跨多台机器的部署。 |
为了避免初始化问题,由 Pivotal GemFire 的 Spring Data 启动的 CacheServer 在 Spring 容器完全初始化之后才启动。这样做可以让声明性定义的潜在区域、监听器、写入器或实例化器在服务器开始接受连接之前完全初始化和注册。在以编程方式配置这些元素时请记住这一点,因为服务器可能会在您的组件之前启动,因此不会立即被连接的客户端看到。 |
5.4.3. 配置 Pivotal GemFire ClientCache
除了定义 Pivotal GemFire 对等 Cache 之外,Pivotal GemFire 的 Spring Data 还支持在 Spring 容器中定义 Pivotal GemFire ClientCache。ClientCache 定义在配置和使用上与 Pivotal GemFire 对等 Cache 类似,并受 org.springframework.data.gemfire.client.ClientCacheFactoryBean 支持。
使用默认配置的 Pivotal GemFire 缓存客户端的最简单定义如下
<beans>
<gfe:client-cache/>
</beans>
client-cache 支持与缓存元素相同的许多选项。但是,与功能齐全的对等 Cache 成员不同,缓存客户端通过池连接到远程缓存服务器。默认情况下,会创建一个池来连接到在 localhost 上运行并侦听端口 40404 的服务器。默认池由所有客户端区域使用,除非该区域配置为使用特定池。
池可以使用 pool 元素定义。此客户端池可用于直接配置与服务器的连接,用于单个实体或通过一个或多个定位器用于整个缓存。
例如,要自定义 client-cache 使用的默认池,开发人员需要定义一个池并将其连接到缓存定义,如以下示例所示
<beans>
<gfe:client-cache id="myCache" pool-name="myPool"/>
<gfe:pool id="myPool" subscription-enabled="true">
<gfe:locator host="${gemfire.locator.host}" port="${gemfire.locator.port}"/>
</gfe:pool>
</beans>
<client-cache> 元素还有一个 ready-for-events 属性。如果该属性设置为 true,则客户端缓存初始化将包含对 ClientCache.readyForEvents() 的调用。
客户端区域 更详细地介绍了客户端配置。
Pivotal GemFire 的 DEFAULT 池和 Pivotal GemFire 的 Spring Data 池定义
如果 Pivotal GemFire ClientCache 仅为本地,则不需要池定义。例如,您可以定义以下内容
<gfe:client-cache/>
<gfe:client-region id="Example" shortcut="LOCAL"/>
在这种情况下,“Example”区域是 LOCAL,客户端和服务器之间不分发数据。因此,不需要池。这对于任何客户端的、仅本地的区域都适用,如 Pivotal GemFire 的 ClientRegionShortcut(所有 LOCAL_* 快捷方式)所定义。
但是,如果客户端区域是服务器端区域的(缓存)代理,则需要一个池。在这种情况下,有几种定义和使用池的方法。
当 ClientCache、池和基于代理的区域都已定义但未明确标识时,Pivotal GemFire 的 Spring Data 会自动解析引用,如以下示例所示
<gfe:client-cache/>
<gfe:pool>
<gfe:locator host="${geode.locator.host}" port="${geode.locator.port}"/>
</gfe:pool>
<gfe:client-region id="Example" shortcut="PROXY"/>
在前面的示例中,ClientCache 被标识为 gemfireCache,池被标识为 gemfirePool,客户端区域被标识为“Example”。但是,ClientCache 从 gemfirePool 初始化 Pivotal GemFire 的 DEFAULT 池,并且客户端区域在客户端和服务器之间分发数据时使用 gemfirePool。
基本上,Pivotal GemFire 的 Spring Data 会将上述配置解析为以下内容
<gfe:client-cache id="gemfireCache" pool-name="gemfirePool"/>
<gfe:pool id="gemfirePool">
<gfe:locator host="${geode.locator.host}" port="${geode.locator.port}"/>
</gfe:pool>
<gfe:client-region id="Example" cache-ref="gemfireCache" pool-name="gemfirePool" shortcut="PROXY"/>
Pivotal GemFire 仍然会创建一个名为 DEFAULT 的池。Pivotal GemFire 的 Spring Data 会导致 DEFAULT 池从 gemfirePool 初始化。这在定义了多个池且客户端区域使用单独的池,或者根本没有声明池的情况下非常有用。
考虑以下情况
<gfe:client-cache pool-name="locatorPool"/>
<gfe:pool id="locatorPool">
<gfe:locator host="${geode.locator.host}" port="${geode.locator.port}"/>
</gfe:pool>
<gfe:pool id="serverPool">
<gfe:server host="${geode.server.host}" port="${geode.server.port}"/>
</gfe:pool>
<gfe:client-region id="Example" pool-name="serverPool" shortcut="PROXY"/>
<gfe:client-region id="AnotherExample" shortcut="CACHING_PROXY"/>
<gfe:client-region id="YetAnotherExample" shortcut="LOCAL"/>
在此设置中,Pivotal GemFire client-cache 的 DEFAULT 池从 locatorPool 初始化,如 pool-name 属性所指定。没有 Spring Data for Pivotal GemFire 定义的 gemfirePool,因为这两个池都已显式标识(命名)——分别为 locatorPool 和 serverPool。
“Example”区域明确引用并专门使用 serverPool。AnotherExample 区域使用 Pivotal GemFire 的 DEFAULT 池,该池再次根据客户端缓存 bean 定义的 pool-name 属性从 locatorPool 配置。
最后,YetAnotherExample 区域不使用池,因为它是一个 LOCAL 区域。
AnotherExample 区域首先会查找名为 gemfirePool 的池 bean,但这需要定义一个匿名池 bean(即 <gfe:pool/>)或一个显式命名为 gemfirePool 的池 bean(例如 <gfe:pool id="gemfirePool"/>)。 |
如果我们更改 locatorPool 的名称为 gemfirePool,或者使池 bean 定义为匿名,它将与前面配置具有相同的效果。 |
5.5. 配置区域
需要一个区域来从缓存中存储和检索数据。org.apache.geode.cache.Region 是一个扩展 java.util.Map 的接口,支持使用熟悉的键值语义进行基本数据访问。Region 接口被连接到需要它的应用程序类,因此实际的区域类型与编程模型解耦。通常,每个区域与一个域对象关联,类似于关系数据库中的表。
Pivotal GemFire 实现以下类型的区域
-
REPLICATE - 数据在集群中定义该区域的所有缓存成员之间复制。这提供了非常高的读取性能,但写入需要更长时间才能执行复制。
-
PARTITION - 数据在集群中定义该区域的许多缓存成员之间分区(分片)到桶中。这提供了高读取和写入性能,适用于单个节点过大的大型数据集。
-
LOCAL - 数据仅存在于本地节点。
-
Client - 从技术上讲,客户端区域是一个 LOCAL 区域,它充当集群中缓存服务器上托管的 REPLICATE 或 PARTITION 区域的 PROXY。它可以保存本地创建或获取的数据。或者,它可以为空。本地更新会同步到缓存服务器。此外,客户端区域可以订阅事件,以便与源自访问同一服务器区域的远程进程的更改保持最新(同步)。
有关各种区域类型及其功能以及配置选项的更多信息,请参阅 Pivotal GemFire 关于区域类型的文档。
5.5.1. 使用外部配置的区域
要引用已在 Pivotal GemFire 本地 cache.xml 文件中配置的区域,请使用 lookup-region 元素。只需使用 name 属性声明目标区域名称。例如,要为名为 Orders 的现有区域声明一个标识为 ordersRegion 的 bean 定义,您可以使用以下 bean 定义
<gfe:lookup-region id="ordersRegion" name="Orders"/>
如果未指定 name,则 bean 的 id 将用作区域的名称。上面的示例变为
<!-- lookup for a Region called 'Orders' -->
<gfe:lookup-region id="Orders"/>
| 如果区域不存在,将抛出初始化异常。要配置新区域,请继续阅读下面的相应部分。 |
在前面的示例中,由于未明确定义缓存名称,因此使用了默认命名约定 (gemfireCache)。或者,可以使用 cache-ref 属性引用缓存 bean
<gfe:cache id="myCache"/>
<gfe:lookup-region id="ordersRegion" name="Orders" cache-ref="myCache"/>
lookup-region 允许您检索现有、预配置的区域,而无需暴露区域语义或设置基础设施。
5.5.2. 自动区域查找
当您在 <gfe:cache> 元素上使用 cache-xml-location 属性时,auto-region-lookup 允许您将 Pivotal GemFire 本机 cache.xml 文件中定义的所有区域导入到 Spring ApplicationContext 中。
例如,考虑以下 cache.xml 文件
<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="https://geode.apache.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://geode.apache.org/schema/cache https://geode.apache.org/schema/cache/cache-1.0.xsd"
version="1.0">
<region name="Parent" refid="REPLICATE">
<region name="Child" refid="REPLICATE"/>
</region>
</cache>
您可以按如下方式导入上述 cache.xml 文件
<gfe:cache cache-xml-location="cache.xml"/>
然后,您可以使用 <gfe:lookup-region> 元素(例如,<gfe:lookup-region id="Parent"/>)将特定区域引用为 Spring 容器中的 bean,或者您可以选择通过使用以下内容导入 cache.xml 中定义的所有区域
<gfe:auto-region-lookup/>
Pivotal GemFire 的 Spring Data 会自动为 cache.xml 中定义的所有尚未通过显式 <gfe:lookup-region> bean 声明添加到 Spring 容器的 Pivotal GemFire 区域创建 bean。
重要的是要意识到,Pivotal GemFire 的 Spring Data 使用 Spring BeanPostProcessor 在缓存创建和初始化后对其进行后处理,以确定要添加到 Spring ApplicationContext 中作为 bean 的 Pivotal GemFire 中定义的区域。
您可以像在 Spring ApplicationContext 中定义的任何其他 bean 一样注入这些“自动查找”的区域,但有一个例外:您可能需要定义与“gemfireCache”bean 的 depends-on 关联,如下所示
package example;
import ...
@Repository("appDao")
@DependsOn("gemfireCache")
public class ApplicationDao extends DaoSupport {
@Resource(name = "Parent")
private Region<?, ?> parent;
@Resource(name = "/Parent/Child")
private Region<?, ?> child;
...
}
上述示例仅适用于您使用 Spring 的 component-scan 功能时。
如果您使用 Spring XML 配置声明您的组件,那么您将执行以下操作
<bean class="example.ApplicationDao" depends-on="gemfireCache"/>
这样做可以确保 Pivotal GemFire 缓存和 cache.xml 中定义的所有区域在使用 <gfe:auto-region-lookup> 元素时,在任何具有自动装配引用的组件之前创建。
5.5.3. 配置区域
Pivotal GemFire 的 Spring Data 通过以下元素提供对配置任何类型区域的全面支持
-
本地区域:
<local-region> -
分区区域:
<partitioned-region> -
复制区域:
<replicated-region> -
客户端区域:
<client-region>
有关 区域类型 的全面描述,请参阅 Pivotal GemFire 文档。
常见区域属性
下表列出了所有区域类型可用的属性
| 名称 | 值 | 描述 |
|---|---|---|
cache-ref |
Pivotal GemFire Cache bean 引用 |
定义 Pivotal GemFire Cache 的 bean 名称(默认为 'gemfireCache')。 |
cloning-enabled |
布尔值(默认: |
当 |
close |
布尔值(默认: |
确定区域是否应在关闭时关闭。 |
concurrency-checks-enabled |
布尔值(默认: |
确定成员是否执行检查,以对分布式区域的并发或无序更新提供一致的处理。 |
data-policy |
请参阅 Pivotal GemFire 的 数据策略。 |
区域的数据策略。请注意,并非所有数据策略都支持每种区域类型。 |
destroy |
布尔值(默认: |
确定区域是否应在关闭时销毁。 |
disk-store-ref |
配置的磁盘存储的名称。 |
对通过 |
disk-synchronous |
布尔值(默认: |
确定磁盘存储写入是否同步。 |
id |
任何有效的 bean 名称。 |
如果未指定 |
ignore-if-exists |
布尔值(默认: |
如果缓存中已存在该区域,则忽略此 bean 定义,从而改为查找。 |
ignore-jta |
布尔值(默认: |
确定此区域是否参与 JTA (Java Transaction API) 事务。 |
index-update-type |
|
确定索引是否在条目创建时同步或异步更新。 |
initial-capacity |
整数(默认:16) |
区域条目数量的初始内存分配。 |
key-constraint |
任何有效的完全限定 Java 类名。 |
预期的键类型。 |
load-factor |
浮点数(默认:.75) |
设置用于存储区域条目的底层 |
name |
任何有效的区域名称。 |
区域的名称。如果未指定,则假定为 |
persistent |
*布尔值(默认: |
确定区域是否将条目持久化到本地磁盘(磁盘存储)。 |
shortcut |
请参阅 https://gemfire-98-javadocs.docs.pivotal.io//org/apache/geode/cache/RegionShortcut.html |
此区域的 |
statistics |
布尔值(默认: |
确定区域是否报告统计信息。 |
template |
区域模板的名称。 |
对通过 |
value-constraint |
任何有效的完全限定 Java 类名。 |
预期值类型。 |
CacheListener 实例
CacheListener 实例注册到区域以处理区域事件,例如条目何时创建、更新、销毁等。CacheListener 可以是任何实现 CacheListener 接口的 bean。一个区域可以有多个监听器,通过包含在 *-region 元素中的 cache-listener 元素声明。
以下示例有两个声明的 CacheListener。第一个引用了一个命名的顶级 Spring bean。第二个是一个匿名内部 bean 定义。
<bean id="myListener" class="org.example.app.geode.cache.SimpleCacheListener"/>
<gfe:replicated-region id="regionWithListeners">
<gfe:cache-listener>
<!-- nested CacheListener bean reference -->
<ref bean="myListener"/>
<!-- nested CacheListener bean definition -->
<bean class="org.example.app.geode.cache.AnotherSimpleCacheListener"/>
</gfe:cache-listener>
</gfe:replicated-region>
以下示例使用 cache-listener 元素的另一种形式,带有 ref 属性。这样做允许在定义单个 CacheListener 时进行更简洁的配置。
注意:XML 命名空间只允许一个 cache-listener 元素,因此必须使用前面示例中所示的样式或以下示例中的样式。
<beans>
<gfe:replicated-region id="exampleReplicateRegionWithCacheListener">
<gfe:cache-listener ref="myListener"/>
</gfe:replicated-region>
<bean id="myListener" class="example.CacheListener"/>
</beans>
在 cache-listener 元素中使用 ref 和嵌套声明是非法的。这两种选项是互斥的,在同一元素中使用两者会导致异常。 |
|
Bean 引用约定
|
CacheLoaders 和 CacheWriters
与 cache-listener 类似,XML 命名空间提供 cache-loader 和 cache-writer 元素来为区域注册这些 Pivotal GemFire 组件。
CacheLoader 在缓存未命中时调用,以允许从外部数据源(如数据库)加载条目。CacheWriter 在条目创建或更新之前调用,以允许条目同步到外部数据源。主要区别在于 Pivotal GemFire 最多支持每个区域一个 CacheLoader 和 CacheWriter 实例。但是,可以使用任何一种声明样式。
以下示例声明了一个同时具有 CacheLoader 和 CacheWriter 的区域
<beans>
<gfe:replicated-region id="exampleReplicateRegionWithCacheLoaderAndCacheWriter">
<gfe:cache-loader ref="myLoader"/>
<gfe:cache-writer>
<bean class="example.CacheWriter"/>
</gfe:cache-writer>
</gfe:replicated-region>
<bean id="myLoader" class="example.CacheLoader">
<property name="dataSource" ref="mySqlDataSource"/>
</bean>
<!-- DataSource bean definition -->
</beans>
有关详细信息,请参阅 Pivotal GemFire 文档中的 CacheLoader 和 CacheWriter。
5.5.4. 压缩
Pivotal GemFire 区域也可以被压缩,以减少 JVM 内存消耗和压力,从而可能避免全局 GC。当您为区域启用压缩时,存储在区域内存中的所有值都会被压缩,而键和索引保持未压缩。新值在放入区域时被压缩,所有值在从区域读取时自动解压缩。持久化到磁盘或通过网络发送到其他对等成员或客户端时,值不会被压缩。
以下示例显示了一个启用了压缩的区域
<beans>
<gfe:replicated-region id="exampleReplicateRegionWithCompression">
<gfe:compressor>
<bean class="org.apache.geode.compression.SnappyCompressor"/>
</gfe:compressor>
</gfe:replicated-region>
</beans>
有关 区域压缩 的更多信息,请参阅 Pivotal GemFire 的文档。
5.5.5. 堆外内存
Pivotal GemFire 区域还可以配置为将区域值存储在堆外内存中,这部分 JVM 内存不受垃圾回收 (GC) 的影响。通过避免昂贵的 GC 周期,您的应用程序可以将更多时间花在重要的事情上,例如处理请求。
使用堆外内存就像声明要使用的内存量,然后启用您的区域使用堆外内存一样简单,如以下配置所示
<util:properties id="gemfireProperties">
<prop key="off-heap-memory-size">200G</prop>
</util:properties>
<gfe:cache properties-ref="gemfireProperties"/>
<gfe:partitioned-region id="ExampleOffHeapRegion" off-heap="true"/>
您可以通过使用 <gfe:cache> 元素设置以下 Pivotal GemFire 配置属性来控制堆外内存管理的其他方面:
<gfe:cache critical-off-heap-percentage="90" eviction-off-heap-percentage"80"/>
Pivotal GemFire 的 ResourceManager 将使用这两个阈值(critical-off-heap-percentage 和 eviction-off-heap-percentage)更有效地管理堆外内存,其方式与 JVM 管理堆内存的方式大致相同。Pivotal GemFire ResourceManager 将通过淘汰旧数据来防止缓存消耗过多的堆外内存。如果堆外管理器无法跟上,则 ResourceManager 会拒绝向缓存添加数据,直到堆外内存管理器释放了足够的内存。
有关 管理堆和堆外内存 的更多信息,请参阅 Pivotal GemFire 的文档。
具体来说,请阅读 管理堆外内存 一节。
5.5.6. 子区域
Pivotal GemFire 的 Spring Data 也支持子区域,允许将区域按分层关系排列。
例如,Pivotal GemFire 允许一个 /Customer/Address 区域和一个不同的 /Employee/Address 区域。此外,子区域可以有自己的子区域和配置。子区域不继承其父区域的属性。区域类型可以根据 Pivotal GemFire 的限制进行混合和匹配。子区域自然声明为区域的子元素。子区域的 name 属性是简单名称。前面的示例可以配置如下
<beans>
<gfe:replicated-region name="Customer">
<gfe:replicated-region name="Address"/>
</gfe:replicated-region>
<gfe:replicated-region name="Employee">
<gfe:replicated-region name="Address"/>
</gfe:replicated-region>
</beans>
请注意,子区域不允许使用 Monospaced ([id]) 属性。子区域以 bean 名称创建(在本例中分别为 /Customer/Address 和 /Employee/Address)。因此,它们可以注入到其他应用程序 bean 中,例如 GemfireTemplate,这些 bean 需要它们,通过使用区域的完整路径名。区域的完整路径名也应在 OQL 查询字符串中使用。
5.5.7. 区域模板
Pivotal GemFire 的 Spring Data 也支持区域模板。
此功能允许开发人员一次定义常见的区域配置和属性,并在 Spring ApplicationContext 中声明的许多区域 bean 定义中重用该配置。
Pivotal GemFire 的 Spring Data 在其命名空间中包含五个区域模板标签
| 标签名称 | 描述 |
|---|---|
|
定义通用区域属性。在 XML 命名空间中扩展 |
|
定义常见“本地”区域属性。在 XML 命名空间中扩展 |
|
定义常见“分区”区域属性。在 XML 命名空间中扩展 |
|
定义常见“复制”区域属性。在 XML 命名空间中扩展 |
|
定义常见“客户端”区域属性。在 XML 命名空间中扩展 |
除了标签之外,具体的 <gfe:*-region> 元素(以及抽象的 <gfe:*-region-template> 元素)都有一个 template 属性,用于定义区域从中继承其配置的区域模板。区域模板甚至可以继承自其他区域模板。
以下示例显示了一种可能的配置
<beans>
<gfe:async-event-queue id="AEQ" persistent="false" parallel="false" dispatcher-threads="4">
<gfe:async-event-listener>
<bean class="example.AeqListener"/>
</gfe:async-event-listener>
</gfe:async-event-queue>
<gfe:region-template id="BaseRegionTemplate" initial-capacity="51" load-factor="0.85" persistent="false" statistics="true"
key-constraint="java.lang.Long" value-constraint="java.lang.String">
<gfe:cache-listener>
<bean class="example.CacheListenerOne"/>
<bean class="example.CacheListenerTwo"/>
</gfe:cache-listener>
<gfe:entry-ttl timeout="600" action="DESTROY"/>
<gfe:entry-tti timeout="300 action="INVLIDATE"/>
</gfe:region-template>
<gfe:region-template id="ExtendedRegionTemplate" template="BaseRegionTemplate" load-factor="0.55">
<gfe:cache-loader>
<bean class="example.CacheLoader"/>
</gfe:cache-loader>
<gfe:cache-writer>
<bean class="example.CacheWriter"/>
</gfe:cache-writer>
<gfe:async-event-queue-ref bean="AEQ"/>
</gfe:region-template>
<gfe:partitioned-region-template id="PartitionRegionTemplate" template="ExtendedRegionTemplate"
copies="1" load-factor="0.70" local-max-memory="1024" total-max-memory="16384" value-constraint="java.lang.Object">
<gfe:partition-resolver>
<bean class="example.PartitionResolver"/>
</gfe:partition-resolver>
<gfe:eviction type="ENTRY_COUNT" threshold="8192000" action="OVERFLOW_TO_DISK"/>
</gfe:partitioned-region-template>
<gfe:partitioned-region id="TemplateBasedPartitionRegion" template="PartitionRegionTemplate"
copies="2" local-max-memory="8192" persistent="true" total-buckets="91"/>
</beans>
区域模板也适用于子区域。请注意,“TemplateBasedPartitionRegion”扩展了“PartitionRegionTemplate”,后者扩展了“ExtendedRegionTemplate”,后者又扩展了“BaseRegionTemplate”。后续继承的区域 bean 定义中定义的属性和子元素会覆盖父级中的内容。
模板的工作原理
Spring Data for Pivotal GemFire 在解析 Spring ApplicationContext 配置元数据时应用 Region 模板,因此,Region 模板必须按照继承顺序声明。换句话说,父模板必须在子模板之前定义。这样做可以确保应用正确的配置,尤其是在覆盖元素属性或子元素时。
同样重要的是要记住,Region 类型只能从其他类似类型的 Region 继承。例如,<gfe:replicated-region> 不能从 <gfe:partitioned-region-template> 继承。 |
| Region 模板是单继承的。 |
关于 Region、子 Region 和查找的注意事项
以前,Spring Data for Pivotal GemFire XML 命名空间中的 replicated-region、partitioned-region、local-region 和 client-region 元素的一个底层属性是先执行查找,然后再尝试创建 Region。这是为了以防 Region 已经存在,例如 Region 在导入的 Pivotal GemFire 本机 cache.xml 配置文件中定义的情况。因此,首先执行查找以避免任何错误。这是设计使然,可能会更改。
此行为已更改,现在默认行为是首先创建 Region。如果 Region 已存在,则创建逻辑会快速失败并抛出适当的异常。然而,与 CREATE TABLE IF NOT EXISTS … DDL 语法非常相似,Spring Data for Pivotal GemFire <gfe:*-region> XML 命名空间元素现在包含一个 ignore-if-exists 属性,它通过在尝试创建 Region 之前首先按名称查找现有 Region 来恢复旧行为。如果按名称找到现有 Region 且 ignore-if-exists 设置为 true,则 Spring 配置中定义的 Region bean 定义将被忽略。
Spring 团队强烈建议 replicated-region、partitioned-region、local-region 和 client-region XML 命名空间元素仅用于定义新的 Region。当这些元素定义的 Region 已经存在且 Region 元素首先执行查找时,可能会出现一个问题:如果您在应用程序配置中定义了不同的 Region 语义和行为,例如用于逐出、过期、订阅等,那么 Region 定义可能不匹配,并且可能表现出与应用程序要求相反的行为。更糟糕的是,您可能希望将 Region 定义为分布式 Region(例如 PARTITION),而实际上,现有 Region 定义只是本地的。 |
推荐实践 - 仅使用 replicated-region、partitioned-region、local-region 和 client-region XML 命名空间元素来定义新的 Region。 |
考虑以下 Pivotal GemFire 本机 cache.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="https://geode.apache.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://geode.apache.org/schema/cache https://geode.apache.org/schema/cache/cache-1.0.xsd"
version="1.0">
<region name="Customers" refid="REPLICATE">
<region name="Accounts" refid="REPLICATE">
<region name="Orders" refid="REPLICATE">
<region name="Items" refid="REPLICATE"/>
</region>
</region>
</region>
</cache>
此外,考虑您可能已定义如下应用程序 DAO
public class CustomerAccountDao extends GemDaoSupport {
@Resource(name = "Customers/Accounts")
private Region customersAccounts;
...
}
在这里,我们将对 Customers/Accounts Region 的引用注入到我们的应用程序 DAO 中。因此,开发人员在 Spring XML 配置元数据中为其中一些或所有 Region 定义 bean 并不罕见,如下所示
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
">
<gfe:cache cache-xml-location="classpath:cache.xml"/>
<gfe:lookup-region name="Customers/Accounts"/>
<gfe:lookup-region name="Customers/Accounts/Orders"/>
</beans>
Customers/Accounts 和 Customers/Accounts/Orders Region 在 Spring 容器中分别作为 Customers/Accounts 和 Customers/Accounts/Orders bean 引用。使用 lookup-region 元素和相应的语法(前面已描述)的好处是,它允许您直接引用子 Region,而无需不必要地为父 Region(在本例中为 Customers)定义 bean。
考虑以下错误示例,它将配置元数据语法更改为使用嵌套格式
<gfe:lookup-region name="Customers">
<gfe:lookup-region name="Accounts">
<gfe:lookup-region name="Orders"/>
</gfe:lookup-region>
</gfe:lookup-region>
现在考虑另一个错误示例,它使用顶级 replicated-region 元素以及 ignore-if-exists 属性设置为首先执行查找
<gfe:replicated-region name="Customers" persistent="true" ignore-if-exists="true">
<gfe:replicated-region name="Accounts" persistent="true" ignore-if-exists="true">
<gfe:replicated-region name="Orders" persistent="true" ignore-if-exists="true"/>
</gfe:replicated-region>
</gfe:replicated-region>
Spring ApplicationContext 中定义的 Region bean 包含以下内容:{ "Customers", "/Customers/Accounts", "/Customers/Accounts/Orders" }。这意味着前面示例中显示的依赖注入引用(即 @Resource(name = "Customers/Accounts"))现在已损坏,因为实际上没有定义名为 Customers/Accounts 的 bean。因此,您不应按照前面两个示例所示配置 Region。
Pivotal GemFire 在引用父 Region 和子 Region 时既可以带前导斜杠,也可以不带。例如,父级可以引用为 /Customers 或 Customers,子级可以引用为 /Customers/Accounts 或 Customers/Accounts。然而,Spring Data for Pivotal GemFire 在根据 Region 命名 bean 时非常具体。它始终使用斜杠 (/) 来表示子 Region(例如 /Customers/Accounts)。
因此,您应该使用前面所示的非嵌套 lookup-region 语法,或者使用前导斜杠 (/) 定义直接引用,如下所示
<gfe:lookup-region name="/Customers/Accounts"/>
<gfe:lookup-region name="/Customers/Accounts/Orders"/>
前面的示例,其中嵌套的 replicated-region 元素用于引用子 Region,显示了前面所述的问题。Customers、Accounts 和 Orders Region 及子 Region 是否持久?它们不是持久的,因为这些 Region 在 Pivotal GemFire 本机 cache.xml 配置文件中定义为 REPLICATE,并且在缓存 bean 初始化之前(一旦 <gfe:cache> 元素被处理)就已存在。
5.5.8. 数据逐出(带溢出)
根据各种约束,每个 Region 都可以有一个逐出策略,用于从内存中逐出数据。目前,在 Pivotal GemFire 中,逐出应用于最近最少使用的条目(也称为 LRU)。逐出的条目要么被销毁,要么分页到磁盘(称为“溢出到磁盘”)。
Spring Data for Pivotal GemFire 通过使用嵌套的 eviction 元素支持 PARTITION Region、REPLICATE Region 以及客户端、本地 Region 的所有逐出策略(条目计数、内存和堆使用)。
例如,要配置一个 PARTITION Region,使其在内存大小超过 512 MB 时溢出到磁盘,您可以指定以下配置
<gfe:partitioned-region id="examplePartitionRegionWithEviction">
<gfe:eviction type="MEMORY_SIZE" threshold="512" action="OVERFLOW_TO_DISK"/>
</gfe:partitioned-region>
副本不能使用 local destroy 逐出,因为这会使它们失效。有关更多信息,请参阅 Pivotal GemFire 文档。 |
当配置 Region 以进行溢出时,您应该通过 disk-store 元素配置存储以实现最大效率。
有关逐出策略的详细说明,请参阅 Pivotal GemFire 文档中的 逐出。
5.5.9. 数据过期
Pivotal GemFire 允许您控制条目在缓存中存在的时间。过期是由经过时间驱动的,而不是像逐出那样由条目计数或堆或内存使用情况驱动。一旦条目过期,就不能再从缓存中访问它。
Pivotal GemFire 支持以下过期类型
-
存活时间 (TTL):对象在最后一次创建或更新后可以在缓存中保留的秒数。对于条目,创建和 put 操作的计数器设置为零。当 Region 创建时以及当条目的计数器重置时,Region 计数器会重置。
-
空闲超时 (TTI):对象在最后一次访问后可以在缓存中保留的秒数。对象的空闲超时计数器在其 TTL 计数器重置时重置。此外,当通过 get 操作或
netSearch访问条目时,条目的空闲超时计数器会重置。当其中一个条目的空闲超时重置时,Region 的空闲超时计数器会重置。
这些都可以应用于 Region 本身或 Region 中的条目。Spring Data for Pivotal GemFire 提供 <region-ttl>、<region-tti>、<entry-ttl> 和 <entry-tti> Region 子元素来指定超时值和过期操作。
以下示例显示了一个设置了过期值的 PARTITION Region
<gfe:partitioned-region id="examplePartitionRegionWithExpiration">
<gfe:region-ttl timeout="30000" action="INVALIDATE"/>
<gfe:entry-tti timeout="600" action="LOCAL_DESTROY"/>
</gfe:replicated-region>
有关过期策略的详细说明,请参阅 Pivotal GemFire 文档中的 过期。
基于注解的数据过期
使用 Spring Data for Pivotal GemFire,您可以在单个 Region 条目值上(或者换句话说,直接在应用程序域对象上)定义过期策略和设置。例如,您可以在基于 Session 的应用程序域对象上定义过期策略,如下所示
@Expiration(timeout = "1800", action = "INVALIDATE")
public class SessionBasedApplicationDomainObject {
...
}
您还可以使用 @IdleTimeoutExpiration 和 @TimeToLiveExpiration 注解分别指定 Region 条目上的特定于过期类型的设置,如下例所示
@TimeToLiveExpiration(timeout = "3600", action = "LOCAL_DESTROY")
@IdleTimeoutExpiration(timeout = "1800", action = "LOCAL_INVALIDATE")
@Expiration(timeout = "1800", action = "INVALIDATE")
public class AnotherSessionBasedApplicationDomainObject {
...
}
当指定了多个过期注解类型时,@IdleTimeoutExpiration 和 @TimeToLiveExpiration 都优先于通用 @Expiration 注解,如前面的示例所示。@IdleTimeoutExpiration 和 @TimeToLiveExpiration 互不覆盖。相反,当配置了不同的 Region 条目过期策略(例如 TTL 和 TTI)时,它们相互补充。
|
所有基于
|
Spring Data for Pivotal GemFire 的 @Expiration 注解支持是使用 Pivotal GemFire 的 CustomExpiry 接口实现的。有关更多详细信息,请参阅 Pivotal GemFire 文档中关于 配置数据过期 的内容。
Spring Data for Pivotal GemFire 的 AnnotationBasedExpiration 类(和 CustomExpiry 实现)负责处理 SDG @Expiration 注解,并根据请求适当应用 Region 条目过期的过期策略配置。
要使用 Spring Data for Pivotal GemFire 配置特定的 Pivotal GemFire Region,以将过期策略适当地应用于使用基于 @Expiration 注解的应用程序域对象,您必须
-
在 Spring
ApplicationContext中使用适当的构造函数或便捷的工厂方法之一定义一个AnnotationBasedExpiration类型的 bean。当为特定过期类型(例如空闲超时 (TTI) 或存活时间 (TTL))配置过期时,您应该使用AnnotationBasedExpiration类中的一个工厂方法,如下所示<bean id="ttlExpiration" class="org.springframework.data.gemfire.expiration.AnnotationBasedExpiration" factory-method="forTimeToLive"/> <gfe:partitioned-region id="Example" persistent="false"> <gfe:custom-entry-ttl ref="ttlExpiration"/> </gfe:partitioned-region>要配置空闲超时 (TTI) 过期,请使用
forIdleTimeout工厂方法以及<gfe:custom-entry-tti ref="ttiExpiration"/>元素来设置 TTI。 -
(可选) 使用 Spring Data for Pivotal GemFire 的
@Expiration注解之一:@Expiration、@IdleTimeoutExpiration或@TimeToLiveExpiration,对存储在 Region 中的应用程序域对象进行过期策略和自定义设置注解 -
(可选) 在特定应用程序域对象完全没有使用 Spring Data for Pivotal GemFire 的
@Expiration注解进行注解,但 Pivotal GemFire Region 配置为使用 SDG 的自定义AnnotationBasedExpiration类来确定存储在 Region 中的对象的过期策略和设置的情况下,您可以通过执行以下操作在AnnotationBasedExpirationbean 上设置“默认”过期属性
<bean id="defaultExpirationAttributes" class="org.apache.geode.cache.ExpirationAttributes">
<constructor-arg value="600"/>
<constructor-arg value="#{T(org.apache.geode.cache.ExpirationAction).DESTROY}"/>
</bean>
<bean id="ttiExpiration" class="org.springframework.data.gemfire.expiration.AnnotationBasedExpiration"
factory-method="forIdleTimeout">
<constructor-arg ref="defaultExpirationAttributes"/>
</bean>
<gfe:partitioned-region id="Example" persistent="false">
<gfe:custom-entry-tti ref="ttiExpiration"/>
</gfe:partitioned-region>
您可能已经注意到,Spring Data for Pivotal GemFire 的 @Expiration 注解使用 String 作为属性类型,而不是(可能更合适地)强类型——例如,'timeout' 的 int 和 'action' 的 SDG ExpirationActionType。这是为什么呢?
嗯,这是 Spring Data for Pivotal GemFire 的另一个特性,它利用 Spring 的核心基础设施来实现配置便利:属性占位符和 Spring Expression Language (SpEL) 表达式。
例如,开发人员可以使用 @Expiration 注解属性中的属性占位符指定过期“timeout”和“action”,如下例所示
@TimeToLiveExpiration(timeout = "${geode.region.entry.expiration.ttl.timeout}"
action = "${geode.region.entry.expiration.ttl.action}")
public class ExampleApplicationDomainObject {
...
}
然后,在您的 Spring XML 配置或 JavaConfig 中,您可以声明以下 bean
<util:properties id="expirationSettings">
<prop key="geode.region.entry.expiration.ttl.timeout">600</prop>
<prop key="geode.region.entry.expiration.ttl.action">INVALIDATE</prop>
...
</util:properties>
<context:property-placeholder properties-ref="expirationProperties"/>
这在多个应用程序域对象可能共享相似的过期策略以及您希望外部化配置时都很方便。
但是,您可能需要更动态的过期配置,由运行系统的状态决定。这就是 SpEL 的强大之处,实际上也是推荐的方法。您不仅可以引用 Spring 容器中的 bean 并访问 bean 属性、调用方法等,而且过期“timeout”和“action”的值可以是强类型的。考虑以下示例(它基于前面的示例)
<util:properties id="expirationSettings">
<prop key="geode.region.entry.expiration.ttl.timeout">600</prop>
<prop key="geode.region.entry.expiration.ttl.action">#{T(org.springframework.data.gemfire.expiration.ExpirationActionType).DESTROY}</prop>
<prop key="geode.region.entry.expiration.tti.action">#{T(org.apache.geode.cache.ExpirationAction).INVALIDATE}</prop>
...
</util:properties>
<context:property-placeholder properties-ref="expirationProperties"/>
然后,在您的应用程序域对象上,您可以定义超时和操作,如下所示
@TimeToLiveExpiration(timeout = "@expirationSettings['geode.region.entry.expiration.ttl.timeout']"
action = "@expirationSetting['geode.region.entry.expiration.ttl.action']")
public class ExampleApplicationDomainObject {
...
}
您可以想象,“expirationSettings” bean 可以是一个比简单的 java.util.Properties 实例更有趣、更有用的对象。在前面的示例中,properties 元素 (expirationSettings) 使用 SpEL 将操作值基于实际的 ExpirationAction 枚举类型,如果枚举类型发生变化,这会很快导致识别出故障。
作为一个示例,所有这些都在 Spring Data for Pivotal GemFire 测试套件中进行了演示和测试。有关更多详细信息,请参阅 源代码。
5.5.10. 数据持久性
Region 可以是持久的。Pivotal GemFire 确保您放入配置为持久化的 Region 中的所有数据都以可恢复的方式写入磁盘,以便您下次重新创建 Region 时可以恢复数据。这样做允许在机器或进程故障后,甚至在 Pivotal GemFire 数据节点有序关闭和随后的重启后恢复数据。
要使用 Spring Data for Pivotal GemFire 启用持久性,请在任何 <*-region> 元素上将 persistent 属性设置为 true,如下例所示
<gfe:partitioned-region id="examplePersitentPartitionRegion" persistent="true"/>
持久性也可以通过设置 data-policy 属性来配置。为此,将属性的值设置为 Pivotal GemFire 的 DataPolicy 设置之一,如下例所示
<gfe:partitioned-region id="anotherExamplePersistentPartitionRegion" data-policy="PERSISTENT_PARTITION"/>
DataPolicy 必须与 Region 类型匹配,如果 persistent 属性也明确设置,则必须与 persistent 属性一致。如果 persistent 属性设置为 false 但指定了持久性 DataPolicy(例如 PERSISTENT_REPLICATE 或 PERSISTENT_PARTITION),则会抛出初始化异常。
为了在持久化 Region 时获得最大效率,您应该通过 disk-store 元素配置存储。DiskStore 通过 disk-store-ref 属性引用。此外,Region 可以同步或异步执行磁盘写入。以下示例显示了一个同步 DiskStore
<gfe:partitioned-region id="yetAnotherExamplePersistentPartitionRegion" persistent="true"
disk-store-ref="myDiskStore" disk-synchronous="true"/>
这在 配置 DiskStore 中有进一步讨论。
5.5.11. 订阅策略
Pivotal GemFire 允许配置 点对点 (P2P) 事件消息传递 以控制 Region 接收的条目事件。Spring Data for Pivotal GemFire 提供 <gfe:subscription/> 子元素,用于将 REPLICATE 和 PARTITION Region 上的订阅策略设置为 ALL 或 CACHE_CONTENT。以下示例显示了一个 Region,其订阅策略设置为 CACHE_CONTENT
<gfe:partitioned-region id="examplePartitionRegionWithCustomSubscription">
<gfe:subscription type="CACHE_CONTENT"/>
</gfe:partitioned-region>
5.5.12. 本地 Region
Spring Data for Pivotal GemFire 提供了一个专用的 local-region 元素来创建本地 Region。顾名思义,本地 Region 是独立的,这意味着它们不与任何其他分布式系统成员共享数据。除此之外,所有常见的 Region 配置选项都适用。
以下示例显示了一个最小声明(同样,该示例依赖于 Spring Data for Pivotal GemFire XML 命名约定来连接缓存)
<gfe:local-region id="exampleLocalRegion"/>
在前面的示例中,创建了一个本地 Region(如果不存在同名 Region)。Region 的名称与 bean ID (exampleLocalRegion) 相同,并且 bean 假定存在一个名为 gemfireCache 的 Pivotal GemFire 缓存。
5.5.13. 复制 Region
常见的 Region 类型之一是 REPLICATE Region 或“副本”。简而言之,当 Region 配置为 REPLICATE 时,托管该 Region 的每个成员都会在本地存储该 Region 条目的副本。对 REPLICATE Region 的任何更新都会分发到该 Region 的所有副本。当创建副本时,它会经历一个初始化阶段,在此阶段它会发现其他副本并自动复制所有条目。在一个副本正在初始化时,您仍然可以继续使用其他副本。
所有常见的配置选项都可用于 REPLICATE Region。Spring Data for Pivotal GemFire 提供了一个 replicated-region 元素。以下示例显示了一个最小声明
<gfe:replicated-region id="exampleReplica"/>
有关更多详细信息,请参阅 Pivotal GemFire 文档中关于 分布式和复制 Region 的内容。
5.5.14. 分区 Region
Spring Data for Pivotal GemFire XML 命名空间还支持 PARTITION Region。
引用 Pivotal GemFire 文档
“分区区域是一个区域,其中数据在托管该区域的对等服务器之间进行划分,以便每个对等服务器存储数据的一个子集。使用分区区域时,应用程序会呈现一个逻辑视图,该视图看起来像一个包含区域中所有数据的单个映射。对此映射的读取或写入会透明地路由到托管作为操作目标的条目的对等服务器。Pivotal GemFire 将哈希码域划分为桶。每个桶都分配给一个特定的对等服务器,但可能随时重新定位到另一个对等服务器,以提高整个集群中资源的利用率。”
使用 partitioned-region 元素创建 PARTITION Region。其配置选项类似于 replicated-region,并增加了分区特定的功能,例如冗余副本的数量、总最大内存、桶的数量、分区解析器等。
以下示例显示了如何设置具有两个冗余副本的 PARTITION Region
<gfe:partitioned-region id="examplePartitionRegion" copies="2" total-buckets="17">
<gfe:partition-resolver>
<bean class="example.PartitionResolver"/>
</gfe:partition-resolver>
</gfe:partitioned-region>
有关更多详细信息,请参阅 Pivotal GemFire 文档中关于 分区 Region 的内容。
分区 Region 属性
下表提供了 PARTITION Region 特定配置选项的快速概述。这些选项是 前面 描述的常见 Region 配置选项的补充。
| 名称 | 值 | 描述 |
|---|---|---|
副本 |
0..4 |
每个分区的高可用性副本数量。默认情况下,不创建副本,这意味着没有冗余。每个副本都以额外的存储为代价提供额外的备份。 |
共置于 |
有效区域名称 |
此新创建的 |
本地最大内存 |
正整数 |
此进程中该区域使用的最大内存量(以兆字节为单位)。 |
总最大内存 |
任意整数值 |
所有进程中该区域使用的最大内存量(以兆字节为单位)。 |
分区监听器 |
bean 名称 |
此区域用于处理分区事件的 |
分区解析器 |
bean 名称 |
此区域用于自定义分区的 |
恢复延迟 |
任意长整型值 |
在另一个成员崩溃后,现有成员在满足冗余之前等待的延迟(以毫秒为单位)。-1(默认值)表示在故障后不恢复冗余。 |
启动恢复延迟 |
任意长整型值 |
新成员在满足冗余之前等待的延迟(以毫秒为单位)。-1 表示添加新成员不会触发冗余恢复。默认是在添加新成员时立即恢复冗余。 |
5.5.15. 客户端 Region
Pivotal GemFire 支持各种部署拓扑以管理和分发数据。Pivotal GemFire 拓扑的主题超出了本文档的范围。然而,快速回顾一下,Pivotal GemFire 支持的拓扑可以分为:点对点 (p2p)、客户端-服务器和广域网 (WAN)。在后两种配置中,通常声明连接到缓存服务器的客户端 Region。
Spring Data for Pivotal GemFire 通过其 客户端缓存 元素(client-region 和 pool)为每种配置提供专用支持。顾名思义,client-region 定义了一个客户端 Region,而 pool 定义了一个由各种客户端 Region 使用和共享的连接池。
以下示例显示了典型的客户端 Region 配置
<bean id="myListener" class="example.CacheListener"/>
<!-- client Region using the default SDG gemfirePool Pool -->
<gfe:client-region id="Example">
<gfe:cache-listener ref="myListener"/>
</gfe:client-region>
<!-- client Region using its own dedicated Pool -->
<gfe:client-region id="AnotherExample" pool-name="myPool">
<gfe:cache-listener ref="myListener"/>
</gfe:client-region>
<!-- Pool definition -->
<gfe:pool id="myPool" subscription-enabled="true">
<gfe:locator host="remoteHost" port="12345"/>
</gfe:pool>
与其他 Region 类型一样,client-region 支持 CacheListener 实例以及 CacheLoader 和 CacheWriter。它还需要一个连接 Pool 来连接一组 Locators 或服务器。每个客户端 Region 都可以有自己的 Pool,或者它们可以共享同一个。如果未指定 Pool,则将使用“DEFAULT”Pool。
在前面的示例中,Pool 配置了一个 Locator。Locator 是一个单独的进程,用于在分布式系统中发现缓存服务器和对等数据成员,建议用于生产系统。还可以通过使用 server 元素将 Pool 配置为直接连接到一个或多个缓存服务器。 |
有关客户端(尤其是 Pool)上可设置的选项的完整列表,请参阅 Spring Data for Pivotal GemFire 模式(“Spring Data for Pivotal GemFire 模式”)和 Pivotal GemFire 文档中关于 客户端-服务器配置 的内容。
客户端兴趣
为了最大程度地减少网络流量,每个客户端可以单独定义自己的“兴趣”策略,向 Pivotal GemFire 指明它实际需要的数据。在 Spring Data for Pivotal GemFire 中,可以为每个客户端 Region 单独定义“兴趣”。支持基于键和基于正则表达式的兴趣类型。
以下示例显示了基于键和基于正则表达式的 interest 类型
<gfe:client-region id="Example" pool-name="myPool">
<gfe:key-interest durable="true" result-policy="KEYS">
<bean id="key" class="java.lang.String">
<constructor-arg value="someKey"/>
</bean>
</gfe:key-interest>
<gfe:regex-interest pattern=".*" receive-values="false"/>
</gfe:client-region>
一个特殊的键 ALL_KEYS 意味着为所有键注册“兴趣”。通过使用正则表达式 ".*" 也可以实现相同的功能。
<gfe:*-interest> 键和正则表达式元素支持三个属性:durable、receive-values 和 result-policy。
durable 表示当客户端连接到集群中的一个或多个服务器时为客户端创建的“兴趣”策略和订阅队列是否在客户端会话之间保持。如果客户端离开并返回,则在客户端断开连接期间,服务器上为客户端维护一个 durable 订阅队列。当客户端重新连接时,客户端会收到在客户端与集群中的服务器断开连接期间发生的任何事件。
集群中的服务器上为客户端定义的每个 Pool 都维护一个订阅队列,并且该 Pool 也已“启用”订阅。订阅队列用于存储(并可能合并)发送到客户端的事件。如果订阅队列是持久的,它将在客户端会话(即连接)之间持久存在,最长可达指定的超时时间。如果客户端未在给定时间范围内返回,则客户端 Pool 订阅队列将被销毁,以减少集群中服务器的资源消耗。如果订阅队列不是 durable,则在客户端断开连接时立即销毁。您需要决定您的客户端是应该接收在断开连接期间发生的事件,还是只需要在重新连接后接收最新的事件。
receive-values 属性指示是否为创建和更新事件接收条目值。如果为 true,则接收值。如果为 false,则只接收失效事件。
最后,'result-policy' 是一个枚举:KEYS、KEYS_VALUE 和 NONE。默认是 KEYS_VALUES。result-policy 控制客户端首次连接以初始化本地缓存时的初始转储,实质上是用与兴趣策略匹配的所有条目的事件来填充客户端。
如前所述,如果没有在 Pool 上启用订阅,客户端侧兴趣注册作用不大。事实上,在没有启用订阅的情况下尝试兴趣注册是错误的。以下示例显示了如何进行此操作
<gfe:pool ... subscription-enabled="true">
...
</gfe:pool>
除了 subscription-enabled,您还可以设置 subscription-ack-interval、subscription-message-tracking-timeout 和 subscription-redundancy。subscription-redundancy 用于控制集群中的服务器应维护多少个订阅队列副本。如果冗余大于 1,并且“主”订阅队列(即服务器)宕机,则“辅助”订阅队列将接管,防止客户端在高可用性场景中错过事件。
除了 Pool 设置之外,服务器端 Region 还使用一个附加属性 enable-subscription-conflation 来控制发送到客户端的事件的合并。这也有助于进一步最小化网络流量,并且在应用程序只关心条目最新值的情况下非常有用。但是,当应用程序保留已发生事件的时间序列时,合并将阻碍该用例。默认值为 false。以下示例显示了服务器上的 Region 配置,其中客户端包含一个相应的客户端 [CACHING_]PROXY Region,该 Region 对此服务器 Region 中的键感兴趣
<gfe:partitioned-region name="ServerSideRegion" enable-subscription-conflation="true">
...
</gfe:partitioned-region>
要控制客户端与集群中的服务器断开连接后,“持久”订阅队列维护的时间量(以秒为单位),请在 <gfe:client-cache> 元素上设置 durable-client-timeout 属性,如下所示
<gfe:client-cache durable-client-timeout="600">
...
</gfe:client-cache>
关于客户端兴趣工作原理和功能的全面深入讨论超出了本文档的范围。
有关更多详细信息,请参阅 Pivotal GemFire 文档中关于 客户端到服务器事件分发 的内容。
5.5.16. JSON 支持
Pivotal GemFire 支持在 Region 中缓存 JSON 文档,并能够使用 Pivotal GemFire OQL(对象查询语言)查询存储的 JSON 文档。JSON 文档在内部使用 JSONFormatter 类进行转换(作为 String),存储为 PdxInstance 类型。
Spring Data for Pivotal GemFire 提供 <gfe-data:json-region-autoproxy/> 元素来启用 AOP 组件,以建议适当的代理 Region 操作,从而有效地封装 JSONFormatter,从而让您的应用程序直接使用 JSON 字符串。
此外,写入 JSON 配置 Region 的 Java 对象会自动使用 Jackson 的 ObjectMapper 转换为 JSON。当这些值被读取回来时,它们将作为 JSON 字符串返回。
默认情况下,<gfe-data:json-region-autoproxy/> 对所有 Region 执行转换。要将此功能应用于选定的 Region,请在 region-refs 属性中提供逗号分隔的 Region bean ID 列表。其他属性包括一个 pretty-print 标志(默认为 false)和 convert-returned-collections。
此外,默认情况下,getAll() 和 values() Region 操作的结果会针对配置的 Region 进行转换。这是通过在本地内存中创建并行数据结构来完成的。这可能会给大型集合带来显著的开销,因此如果您希望禁用这些 Region 操作的自动转换,请将 convert-returned-collections 设置为 false。
某些 Region 操作(特别是那些使用 Pivotal GemFire 专有 Region.Entry 的操作,例如:entries(boolean)、entrySet(boolean) 和 getEntry() 类型)不是 AOP 建议的目标。此外,entrySet() 方法(返回 Set<java.util.Map.Entry<?, ?>>)也不受影响。 |
以下示例配置显示了如何设置 pretty-print 和 convert-returned-collections 属性
<gfe-data:json-region-autoproxy region-refs="myJsonRegion" pretty-print="true" convert-returned-collections="false"/>
此功能也与 GemfireTemplate 操作无缝协作,前提是模板声明为 Spring bean。目前,不支持原生 QueryService 操作。
5.6. 配置索引
Pivotal GemFire 允许在 Region 数据上创建索引(有时也复数形式为 indices),以提高 OQL(对象查询语言)查询的性能。
在 Spring Data for Pivotal GemFire 中,索引使用 index 元素声明,如下例所示
<gfe:index id="myIndex" expression="someField" from="/SomeRegion" type="HASH"/>
在 Spring Data for Pivotal GemFire 的 XML 模式(也称为 SDG XML 命名空间)中,index bean 声明不绑定到 Region,这与 Pivotal GemFire 的原生 cache.xml 不同。相反,它们是顶级元素,类似于 <gfe:cache> 元素。这允许您在任何 Region 上声明任意数量的索引,无论它们是刚刚创建还是已经存在——这是对 Pivotal GemFire 原生 cache.xml 格式的重大改进。
一个 Index 必须有一个名称。您可以使用 name 属性为 Index 提供一个显式名称。否则,index bean 定义的 bean 名称(即 id 属性的值)将用作 Index 名称。
expression 和 from 子句构成 Index 的主要组成部分,它们标识要索引的数据(即 from 子句中标识的 Region)以及用于索引数据的标准(即 expression)。expression 应该基于应用程序定义的 OQL 查询谓词中使用的应用程序域对象字段,这些查询用于查询和查找存储在 Region 中的对象。
考虑以下示例,它有一个 lastName 属性
@Region("Customers")
class Customer {
@Id
Long id;
String lastName;
String firstName;
...
}
现在考虑以下示例,它有一个应用程序定义的 SDG Repository 用于查询 Customer 对象
interface CustomerRepository extends GemfireRepository<Customer, Long> {
Customer findByLastName(String lastName);
...
}
SDG Repository finder/query 方法会生成并运行以下 OQL 语句
SELECT * FROM /Customers c WHERE c.lastName = '$1'
因此,您可能希望创建一个类似于以下语句的 Index
<gfe:index id="myIndex" name="CustomersLastNameIndex" expression="lastName" from="/Customers" type="HASH"/>
from 子句必须引用一个有效、现有的 Region,并且是 Index 应用于 Region 的方式。这并非 Spring Data for Pivotal GemFire 特有。它是 Pivotal GemFire 的一个特性。
Index type 可以是 Spring Data for Pivotal GemFire 的 IndexType 枚举定义的三个枚举值之一:FUNCTIONAL、HASH 和 PRIMARY_KEY。
每个枚举值对应于实际 Index 创建时(或“定义”时——您可以在下一节中找到更多关于“定义”索引的信息)调用的 QueryService create[|Key|Hash]Index 方法之一。例如,如果 IndexType 是 PRIMARY_KEY,则调用 QueryService.createKeyIndex(..) 来创建 KEY Index。
默认是 FUNCTIONAL,并导致调用 QueryService.createIndex(..) 方法之一。有关完整选项集,请参阅 Spring Data for Pivotal GemFire XML 模式。
有关 Pivotal GemFire 中索引的更多信息,请参阅 Pivotal GemFire 用户指南中的“使用索引”。
5.6.1. 定义索引
除了在 Spring Data for Pivotal GemFire 在 Spring 容器初始化时处理 Index bean 定义时预先创建索引之外,您还可以通过使用 define 属性来定义所有应用程序索引,然后再创建它们,如下所示
<gfe:index id="myDefinedIndex" expression="someField" from="/SomeRegion" define="true"/>
当 define 设置为 true(默认为 false)时,它实际上不会立即创建 Index。所有“已定义”的 Index 都会在 Spring ApplicationContext “刷新”时一次性创建,或者换句话说,当 Spring 容器发布 ContextRefreshedEvent 时。Spring Data for Pivotal GemFire 将自己注册为监听 ContextRefreshedEvent 的 ApplicationListener。当触发时,Spring Data for Pivotal GemFire 调用 QueryService.createDefinedIndexes()。
定义索引并一次性创建它们可以提高创建索引的速度和效率。
有关更多详细信息,请参阅“一次创建多个索引”。
5.6.2. IgnoreIfExists 和 Override
两个 Spring Data for Pivotal GemFire Index 配置选项值得特别提及:ignoreIfExists 和 override。
这些选项分别对应于 Spring Data for Pivotal GemFire 的 XML 命名空间中 <gfe:index> 元素上的 ignore-if-exists 和 override 属性。
在使用这些选项之前,请务必完全理解您正在做什么。这些选项会影响应用程序在运行时消耗的性能和资源(例如内存)。因此,SDG 默认禁用(设置为 false)这两个选项。 |
| 这些选项仅在 Spring Data for Pivotal GemFire 中可用,并且旨在解决 Pivotal GemFire 的已知限制。Pivotal GemFire 没有等效的选项或功能。 |
每个选项在行为上都显著不同,并且完全取决于抛出的 Pivotal GemFire Index 异常类型。这也意味着如果未抛出 Pivotal GemFire Index 类型异常,则两个选项均无效。这些选项旨在专门处理 Pivotal GemFire IndexExistsException 和 IndexNameConflictException 实例,这些实例可能由于各种(有时是模糊的)原因而发生。这些异常有以下原因
-
当存在另一个具有相同定义但名称不同的
Index时,在尝试创建Index时会抛出IndexExistsException。 -
当存在另一个具有相同名称但定义可能不同的
Index时,在尝试创建Index时会抛出IndexNameConflictException。
Spring Data for Pivotal GemFire 的默认行为是始终快速失败。因此,默认情况下不会“处理”任何 Index Exception。这些 Index 异常被包装在 SDG GemfireIndexException 中并重新抛出。如果您希望 Spring Data for Pivotal GemFire 为您处理它们,您可以将这些 Index bean 定义选项中的任何一个设置为 true。
IgnoreIfExists 总是优先于 Override,主要是因为它使用的资源更少,仅仅因为它在这两种异常情况下都返回“现有”的 Index。
IgnoreIfExists 行为
当抛出 IndexExistsException 并且 ignoreIfExists 设置为 true(或 <gfe:index ignore-if-exists="true">)时,此 index bean 定义或声明本应创建的 Index 会被简单地忽略,并返回现有的 Index。
返回现有 Index 几乎没有后果,因为 index bean 定义是相同的,这是由 Pivotal GemFire 本身而不是 SDG 决定的。
然而,这也意味着从 Pivotal GemFire 的角度来看(即,使用 QueryService.getIndexes()),实际上不存在您的 index bean 定义或声明中指定的“name”的 Index。因此,在编写使用查询提示的 OQL 查询语句时应谨慎,特别是引用被忽略的应用程序 Index 的查询提示。这些查询提示需要更改。
当抛出 IndexNameConflictException 并且 ignoreIfExists 设置为 true(或 <gfe:index ignore-if-exists="true">)时,此 index bean 定义或声明本应创建的 Index 也被忽略,并且再次返回“现有”的 Index,就像抛出 IndexExistsException 时一样。
然而,当抛出 IndexNameConflictException 时,返回现有 Index 并忽略应用程序定义的 Index 的风险更大。对于 IndexNameConflictException,虽然冲突索引的名称相同,但定义可能不同。这种情况可能对应用程序特定的 OQL 查询产生影响,您可能会假定索引是根据应用程序数据访问模式和查询专门定义的。但是,如果同名索引在定义上有所不同,则可能不是这种情况。因此,您应该验证您的 Index 名称。
当被忽略的 Index 在定义上与现有 Index 显著不同时,SDG 会尽力通知用户。但是,为了让 SDG 完成此操作,它必须能够找到现有 Index,这是通过使用 Pivotal GemFire API(唯一可用的方式)查找的。 |
Override 行为
当抛出 IndexExistsException 并且 override 设置为 true(或 <gfe:index override="true">)时,Index 会被有效地重命名。请记住,当存在多个具有相同定义但名称不同的索引时,会抛出 IndexExistsExceptions。
Spring Data for Pivotal GemFire 只能通过使用 Pivotal GemFire 的 API 来实现这一点,即首先删除现有 Index,然后使用新名称重新创建 Index。删除或后续创建调用都可能失败。无法原子地执行这两个操作并在其中任何一个失败时回滚此联合操作。
但是,如果成功,那么您将面临与 ignoreIfExists 选项之前相同的问题。任何使用引用旧 Index 名称的查询提示的现有 OQL 查询语句都必须更改。
当抛出 IndexNameConflictException 并且 override 设置为 true(或 <gfe:index override="true">)时,现有 Index 可能会被重新定义。我们说“可能”是因为当抛出 IndexNameConflictException 时,同名现有 Index 可能具有完全相同的定义和名称。
如果是这样,SDG 会很聪明,即使在 override 的情况下也会按原样返回现有 Index。这种行为没有害处,因为名称和定义完全相同。当然,SDG 只有在能够找到现有 Index 时才能实现这一点,这取决于 Pivotal GemFire 的 API。如果找不到,则什么都不会发生,并且会抛出一个包装了 IndexNameConflictException 的 SDG GemfireIndexException。
但是,当现有 Index 的定义不同时,SDG 会尝试使用 index bean 定义中指定的 Index 定义重新创建 Index。确保这是您想要的,并确保 index bean 定义符合您的期望和应用程序要求。
IndexNameConflictExceptions 究竟是如何发生的?
抛出 IndexExistsExceptions 并不罕见,尤其是在使用多个配置源来配置 Pivotal GemFire(Spring Data for Pivotal GemFire、Pivotal GemFire 集群配置、Pivotal GemFire 原生 cache.xml、API 等)时。您应该明确选择一种配置方法并坚持使用。
但是,什么时候会抛出 IndexNameConflictException 呢?
一个特定情况是在 PARTITION Region (PR) 上定义的 Index。当在 PARTITION Region(例如 X)上定义 Index 时,Pivotal GemFire 会将 Index 定义(和名称)分发到集群中也托管相同 PARTITION Region(即“X”)的其他对等成员。将此 Index 定义分发给对等成员并随后由对等成员创建此 Index 是基于按需原则(即由托管相同 PR 的对等成员)异步执行的。
在此时间窗口内,这些挂起的 PR Indexes 可能无法被 Pivotal GemFire 识别——例如,通过调用 QueryService.getIndexes()(带 QueryService.getIndexes(:Region)),甚至通过 QueryService.getIndex(:Region, indexName:String)。
因此,SDG 或其他 Pivotal GemFire 缓存客户端应用程序(不涉及 Spring)唯一确定知道的方法是尝试创建 Index。如果它因 IndexNameConflictException 甚至 IndexExistsException 而失败,应用程序就知道存在问题。这是因为 QueryService Index 创建会等待挂起的 Index 定义,而其他 Pivotal GemFire API 调用不会。
无论如何,SDG 会尽力通知您发生了什么或正在发生什么,并告诉您纠正措施。鉴于所有 Pivotal GemFire QueryService.createIndex(..) 方法都是同步的阻塞操作,在抛出这些索引类型异常后,Pivotal GemFire 的状态应该是一致且可访问的。因此,SDG 可以根据您的配置检查系统状态并采取相应行动。
在所有其他情况下,SDG 采用快速失败策略。
5.7. 配置 DiskStore
Spring Data for Pivotal GemFire 通过 disk-store 元素支持 DiskStore 配置和创建,如下例所示
<gfe:disk-store id="Example" auto-compact="true" max-oplog-size="10"
queue-size="50" time-interval="9999">
<gfe:disk-dir location="/disk/location/one" max-size="20"/>
<gfe:disk-dir location="/disk/location/two" max-size="20"/>
</gfe:disk-store>
DiskStore 实例用于 Region 的文件系统持久备份和逐出条目的溢出,以及 WAN 网关的持久备份。多个 Pivotal GemFire 组件可以共享同一个 DiskStore。此外,可以为一个 DiskStore 定义多个文件系统目录,如上例所示。
有关 DiskStore 实例上的 持久性和溢出 以及配置选项的完整解释,请参阅 Pivotal GemFire 文档。
5.8. 配置快照服务
Spring Data for Pivotal GemFire 通过使用 Pivotal GemFire 的快照服务 支持缓存和 Region 快照。开箱即用的快照服务支持提供了一些便捷功能,以简化 Pivotal GemFire 的 缓存 和 Region 快照服务 API 的使用。
正如 Pivotal GemFire 文档 所解释的,快照允许您保存并随后重新加载缓存数据,这对于在环境之间移动数据非常有用,例如从生产环境移动到 staging 或测试环境,以便在受控上下文中重现与数据相关的问题。您可以将 Spring Data for Pivotal GemFire 的快照服务支持与 Spring 的 bean 定义配置文件 结合使用,以根据需要加载特定于环境的快照数据。
Spring Data for Pivotal GemFire 对 Pivotal GemFire 快照服务的支持始于 <gfe-data> XML 命名空间中的 <gfe-data:snapshot-service> 元素。
例如,您可以通过使用几个快照导入和一个数据导出定义来定义要加载和保存的缓存范围快照,如下所示
<gfe-data:snapshot-service id="gemfireCacheSnapshotService">
<gfe-data:snapshot-import location="/absolute/filesystem/path/to/import/fileOne.snapshot"/>
<gfe-data:snapshot-import location="relative/filesystem/path/to/import/fileTwo.snapshot"/>
<gfe-data:snapshot-export
location="/absolute/or/relative/filesystem/path/to/export/directory"/>
</gfe-data:snapshot-service>
您可以定义任意数量的导入和导出。您可以只定义导入或只定义导出。文件位置和目录路径可以是绝对的,也可以是相对于 Spring Data for Pivotal GemFire 应用程序(即 JVM 进程的工作目录)的。
前面的示例非常简单,在这种情况下定义的快照服务引用了默认名称为 gemfireCache 的 Pivotal GemFire 缓存实例(如 配置缓存 中所述)。如果您的缓存 bean 定义名称不是默认名称,您可以使用 cache-ref 属性按名称引用缓存 bean,如下所示
<gfe:cache id="myCache"/>
...
<gfe-data:snapshot-service id="mySnapshotService" cache-ref="myCache">
...
</gfe-data:snapshot-service>
您还可以通过指定 region-ref 属性为特定 Region 定义快照服务,如下所示
<gfe:partitioned-region id="Example" persistent="false" .../>
...
<gfe-data:snapshot-service id="gemfireCacheRegionSnapshotService" region-ref="Example">
<gfe-data:snapshot-import location="relative/path/to/import/example.snapshot/>
<gfe-data:snapshot-export location="/absolute/path/to/export/example.snapshot/>
</gfe-data:snapshot-service>
当指定 region-ref 属性时,Spring Data for Pivotal GemFire 的 SnapshotServiceFactoryBean 会将 region-ref 属性值解析为 Spring 容器中定义的 Region bean,并创建一个 RegionSnapshotService。快照导入和导出定义的运作方式相同。但是,location 必须引用导出文件。
| Pivotal GemFire 对导入的快照文件在被引用之前必须实际存在这一点非常严格。对于导出,Pivotal GemFire 会创建快照文件。如果导出的快照文件已存在,则数据将被覆盖。 |
Spring Data for Pivotal GemFire 在 <gfe-data:snapshot-service> 元素上包含一个 suppress-import-on-init 属性,以阻止配置的快照服务在初始化时尝试将数据导入缓存或 Region。例如,当从一个 Region 导出的数据用于另一个 Region 的导入时,这很有用。 |
5.8.1. 快照位置
对于基于缓存的快照服务(即 CacheSnapshotService),您通常会向它传递一个包含所有快照文件的目录,而不是单个快照文件,正如 CacheSnapshotService API 中重载的 load 方法所示。
当然,您可以使用重载的 load(:File[], :SnapshotFormat, :SnapshotOptions) 方法来具体指定要加载到 Pivotal GemFire 缓存中的快照文件。 |
然而,Spring Data for Pivotal GemFire 认识到,典型的开发人员工作流可能是从一个环境提取和导出数据到几个快照文件,将所有这些文件打包成 zip,然后方便地将 zip 文件移动到另一个环境进行导入。
因此,Spring Data for Pivotal GemFire 允许您在导入基于 cache 的快照服务时指定一个 jar 或 zip 文件,如下所示
<gfe-data:snapshot-service id="cacheBasedSnapshotService" cache-ref="gemfireCache">
<gfe-data:snapshot-import location="/path/to/snapshots.zip"/>
</gfe-data:snapshot-service>
Spring Data for Pivotal GemFire 方便地提取提供的 zip 文件并将其视为目录导入(加载)。
5.8.2. 快照过滤器
定义多个快照导入和导出的真正强大之处在于使用快照过滤器。快照过滤器实现了 Pivotal GemFire 的 SnapshotFilter 接口,并用于过滤 Region 条目,以将其包含在导入时的 Region 中以及导出时的快照中。
Spring Data for Pivotal GemFire 允许您通过使用 filter-ref 属性或匿名嵌套 bean 定义在导入和导出时使用快照过滤器,如下例所示
<gfe:cache/>
<gfe:partitioned-region id="Admins" persistent="false"/>
<gfe:partitioned-region id="Guests" persistent="false"/>
<bean id="activeUsersFilter" class="example.gemfire.snapshot.filter.ActiveUsersFilter/>
<gfe-data:snapshot-service id="adminsSnapshotService" region-ref="Admins">
<gfe-data:snapshot-import location="/path/to/import/users.snapshot">
<bean class="example.gemfire.snapshot.filter.AdminsFilter/>
</gfe-data:snapshot-import>
<gfe-data:snapshot-export location="/path/to/export/active/admins.snapshot" filter-ref="activeUsersFilter"/>
</gfe-data:snapshot-service>
<gfe-data:snapshot-service id="guestsSnapshotService" region-ref="Guests">
<gfe-data:snapshot-import location="/path/to/import/users.snapshot">
<bean class="example.gemfire.snapshot.filter.GuestsFilter/>
</gfe-data:snapshot-import>
<gfe-data:snapshot-export location="/path/to/export/active/guests.snapshot" filter-ref="activeUsersFilter"/>
</gfe-data:snapshot-service>
此外,您可以使用 ComposableSnapshotFilter 类表达更复杂的快照过滤器。该类实现了 Pivotal GemFire 的 SnapshotFilter 接口以及 Composite 软件设计模式。
简而言之,复合 软件设计模式允许您组合多个相同类型的对象并将聚合视为对象类型的单个实例——这是一种强大而有用的抽象。
ComposableSnapshotFilter 有两个工厂方法:and 和 or。它们允许您分别使用 AND 和 OR 逻辑运算符逻辑组合单个快照过滤器。工厂方法接受 SnapshotFilters 列表。
以下示例显示了 ComposableSnapshotFilter 的定义
<bean id="activeUsersSinceFilter" class="org.springframework.data.gemfire.snapshot.filter.ComposableSnapshotFilter"
factory-method="and">
<constructor-arg index="0">
<list>
<bean class="org.example.app.gemfire.snapshot.filter.ActiveUsersFilter"/>
<bean class="org.example.app.gemfire.snapshot.filter.UsersSinceFilter"
p:since="2015-01-01"/>
</list>
</constructor-arg>
</bean>
然后,您可以继续使用 or 将 activesUsersSinceFilter 与另一个过滤器组合,如下所示
<bean id="covertOrActiveUsersSinceFilter" class="org.springframework.data.gemfire.snapshot.filter.ComposableSnapshotFilter"
factory-method="or">
<constructor-arg index="0">
<list>
<ref bean="activeUsersSinceFilter"/>
<bean class="example.gemfire.snapshot.filter.CovertUsersFilter"/>
</list>
</constructor-arg>
</bean>
5.8.3. 快照事件
默认情况下,Spring Data for Pivotal GemFire 在启动时使用 Pivotal GemFire 的快照服务导入数据,在关闭时导出数据。但是,您可能希望在 Spring 应用程序中触发定期的、基于事件的快照,无论是用于导入还是导出。
为此,Spring Data for Pivotal GemFire 定义了两个额外的 Spring 应用程序事件,分别扩展了 Spring 的 ApplicationEvent 类,用于导入和导出:ImportSnapshotApplicationEvent 和 ExportSnapshotApplicationEvent。
这两个应用程序事件可以针对整个 Pivotal GemFire 缓存或单个 Pivotal GemFire Region。这些类中的构造函数接受一个可选的 Region 路径名(例如 /Example)以及零个或多个 SnapshotMetadata 实例。
SnapshotMetadata 数组会覆盖由 <gfe-data:snapshot-import> 和 <gfe-data:snapshot-export> 子元素定义的快照元数据,这些子元素用于快照应用程序事件未明确提供 SnapshotMetadata 的情况。每个单独的 SnapshotMetadata 实例都可以定义自己的 location 和 filters 属性。
Spring ApplicationContext 中定义的所有快照服务 bean 都会接收导入和导出快照应用程序事件。但是,只有匹配的快照服务 bean 才会处理导入和导出事件。
如果定义的快照服务 bean 是 RegionSnapshotService,并且其 Region 引用(由 region-ref 属性确定)与快照应用程序事件指定的 Region 路径名匹配,则基于 Region 的 [Import|Export]SnapshotApplicationEvent 匹配。
基于缓存的 [Import|Export]SnapshotApplicationEvent(即没有 Region 路径名的快照应用程序事件)会触发所有快照服务 bean,包括任何 RegionSnapshotService bean,以分别执行导入或导出。
您可以使用 Spring 的 ApplicationEventPublisher 接口从您的应用程序中触发导入和导出快照应用程序事件,如下所示
@Component
public class ExampleApplicationComponent {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Resource(name = "Example")
private Region<?, ?> example;
public void someMethod() {
...
File dataSnapshot = new File(System.getProperty("user.dir"), "/path/to/export/data.snapshot");
SnapshotFilter myFilter = ...;
SnapshotMetadata exportSnapshotMetadata =
new SnapshotMetadata(dataSnapshot, myFilter, null);
ExportSnapshotApplicationEvent exportSnapshotEvent =
new ExportSnapshotApplicationEvent(this, example.getFullPath(), exportSnapshotMetadata)
eventPublisher.publishEvent(exportSnapshotEvent);
...
}
}
在前面的示例中,只有 /Example Region 的快照服务 bean 接收并处理导出事件,将过滤后的“/Example”Region 的数据保存到应用程序工作目录的子目录中的 data.snapshot 文件中。
使用 Spring 应用程序事件和消息子系统是保持应用程序松散耦合的好方法。您还可以使用 Spring 的 调度 服务定期触发快照应用程序事件。
5.9. 配置函数服务
Spring Data for Pivotal GemFire 提供 注解 支持,用于实现、注册和执行 Pivotal GemFire 函数。
Spring Data for Pivotal GemFire 还提供 XML 命名空间支持,用于注册 Pivotal GemFire 函数 以进行远程函数执行。
有关函数执行框架的更多信息,请参阅 Pivotal GemFire 的 文档。
Pivotal GemFire 函数被声明为 Spring bean,并且必须实现 org.apache.geode.cache.execute.Function 接口或扩展 org.apache.geode.cache.execute.FunctionAdapter。
命名空间使用熟悉的模式声明函数,如下例所示
<gfe:function-service>
<gfe:function>
<bean class="example.FunctionOne"/>
<ref bean="function2"/>
</gfe:function>
</gfe:function-service>
<bean id="function2" class="example.FunctionTwo"/>
5.10. 配置 WAN 网关
WAN 网关提供了一种跨地理位置同步 Pivotal GemFire 分布式系统的方法。Spring Data for Pivotal GemFire 提供 XML 命名空间支持来配置 WAN 网关,如以下示例所示。
5.10.1. Pivotal GemFire 7.0 中的 WAN 配置
在以下示例中,通过向 Region 添加子元素(gateway-sender 和 gateway-sender-ref),为 PARTITION Region 配置了 GatewaySenders。GatewaySender 可以注册 EventFilters 和 TransportFilters。
以下示例还显示了 AsyncEventQueue 的示例配置,它也必须自动装配到 Region 中(未显示)
<gfe:partitioned-region id="region-with-inner-gateway-sender" >
<gfe:gateway-sender remote-distributed-system-id="1">
<gfe:event-filter>
<bean class="org.springframework.data.gemfire.example.SomeEventFilter"/>
</gfe:event-filter>
<gfe:transport-filter>
<bean class="org.springframework.data.gemfire.example.SomeTransportFilter"/>
</gfe:transport-filter>
</gfe:gateway-sender>
<gfe:gateway-sender-ref bean="gateway-sender"/>
</gfe:partitioned-region>
<gfe:async-event-queue id="async-event-queue" batch-size="10" persistent="true" disk-store-ref="diskstore"
maximum-queue-memory="50">
<gfe:async-event-listener>
<bean class="example.AsyncEventListener"/>
</gfe:async-event-listener>
</gfe:async-event-queue>
<gfe:gateway-sender id="gateway-sender" remote-distributed-system-id="2">
<gfe:event-filter>
<ref bean="event-filter"/>
<bean class="org.springframework.data.gemfire.example.SomeEventFilter"/>
</gfe:event-filter>
<gfe:transport-filter>
<ref bean="transport-filter"/>
<bean class="org.springframework.data.gemfire.example.SomeTransportFilter"/>
</gfe:transport-filter>
</gfe:gateway-sender>
<bean id="event-filter" class="org.springframework.data.gemfire.example.AnotherEventFilter"/>
<bean id="transport-filter" class="org.springframework.data.gemfire.example.AnotherTransportFilter"/>
GatewaySender 的另一端是相应的 GatewayReceiver,用于接收网关事件。GatewayReceiver 也可以配置 EventFilters 和 TransportFilters,如下所示
<gfe:gateway-receiver id="gateway-receiver" start-port="12345" end-port="23456" bind-address="192.168.0.1">
<gfe:transport-filter>
<bean class="org.springframework.data.gemfire.example.SomeTransportFilter"/>
</gfe:transport-filter>
</gfe:gateway-receiver>
有关所有配置选项的详细解释,请参阅 Pivotal GemFire 文档。
6. 使用注解将 Pivotal GemFire 与 Spring 容器引导
Spring Data for Pivotal GemFire (SDG) 2.0 引入了一种新的基于注解的配置模型,用于使用 Spring 容器配置和引导 Pivotal GemFire。
在 Spring 上下文中引入基于注解的 Pivotal GemFire 配置方法的主要动机是让 Spring 应用程序开发人员尽可能
让我们开始吧!
| 如果您想更快地开始,请参阅 快速入门 部分。 |
6.1. 简介
鉴于所有 配置属性 和不同的配置选项,Pivotal GemFire 可能难以正确设置和使用
不同支持的拓扑结构带来了进一步的复杂性
基于注解的配置模型旨在简化所有这些及更多。
基于注解的配置模型是使用 Spring Data for Pivotal GemFire 的 XML 命名空间的 XML 配置的替代方案。使用 XML,您可以使用 gfe XML 模式进行配置,并使用 gfe-data XML 模式进行数据访问。有关更多详细信息,请参阅“使用 Spring 容器引导 Pivotal GemFire”。
| 截至 SDG 2.0,基于注解的配置模型尚不支持 Pivotal GemFire WAN 组件和拓扑的配置。 |
与 Spring Boot 一样,Spring Data for Pivotal GemFire 的基于注解的配置模型被设计为一种主观的、约定优于配置的 Pivotal GemFire 使用方法。事实上,这种基于注解的配置模型受到了 Spring Boot 以及多个其他 Spring 和 Spring Data 项目的共同启发。
遵循约定,所有注解都为所有配置属性提供合理且明智的默认值。给定注解属性的默认值直接对应于 Pivotal GemFire 为相同配置属性提供的默认值。
目的是让您通过在 Spring @Configuration 或 @SpringBootApplication 类上声明适当的注解来启用 Pivotal GemFire 功能或嵌入式服务,而无需不必要地配置大量属性即可使用该功能或服务。
再次强调,
但是,如果您需要,可以自定义 Pivotal GemFire 的配置元数据和行为,并且 Spring Data for Pivotal GemFire 的基于注解的配置会悄然退去。您只需指定您希望调整的配置属性。此外,正如我们将在本文档后面看到的那样,有几种方法可以使用注解配置 Pivotal GemFire 功能或嵌入式服务。
您可以在 org.springframework.data.gemfire.config.annotation 包中找到所有新的 SDG Java Annotations。
6.2. 使用 Spring 配置 Pivotal GemFire 应用程序
像所有以 @SpringBootApplication 注解应用程序类开始的 Spring Boot 应用程序一样,Spring Boot 应用程序可以通过声明以下三个主要注解中的任何一个,轻松地成为 Pivotal GemFire 缓存应用程序
-
@ClientCacheApplication -
@PeerCacheApplication -
@CacheServerApplication
这三个注解是 Spring 应用程序开发人员使用 Pivotal GemFire 的起点。
要理解这些注解背后的意图,您必须了解使用 Pivotal GemFire 可以创建两种类型的缓存实例:客户端缓存或对等缓存。
您可以将 Spring Boot 应用程序配置为 Pivotal GemFire 缓存客户端,其中包含 ClientCache 实例,该实例可以与现有的 Pivotal GemFire 服务器集群通信,用于管理应用程序的数据。客户端-服务器拓扑是使用 Pivotal GemFire 时最常见的系统架构,您只需使用 @ClientCacheApplication 注解即可将 Spring Boot 应用程序设置为缓存客户端,并使用 ClientCache 实例。
或者,Spring Boot 应用程序可以是 Pivotal GemFire 集群的对等成员。也就是说,应用程序本身只是服务器集群中的另一个服务器,用于管理数据。当您使用 @PeerCacheApplication 注解应用程序类时,Spring Boot 应用程序会创建一个“嵌入式”对等 Cache 实例。
推而广之,对等缓存应用程序也可以充当 CacheServer,允许缓存客户端连接并对服务器执行数据访问操作。这是通过使用 @CacheServerApplication 注解应用程序类而不是 @PeerCacheApplication 来实现的,它会创建一个对等 Cache 实例以及一个允许缓存客户端连接的 CacheServer。
Pivotal GemFire 服务器默认不一定是缓存服务器。也就是说,服务器不一定仅仅因为它是一个服务器就被设置为服务缓存客户端。Pivotal GemFire 服务器可以是集群的对等成员(数据节点),管理数据,而不服务任何客户端,而集群中的其他对等成员确实被设置为服务客户端,除了管理数据。还可以将集群中的某些对等成员设置为非数据节点,称为 数据访问器,它们不存储数据,但充当服务客户端的代理作为 CacheServers。Pivotal GemFire 支持许多不同的拓扑和集群安排,但这超出了本文档的范围。 |
举例来说,如果您想创建一个 Spring Boot 缓存客户端应用程序,请从以下开始
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
class ClientApplication { .. }
或者,如果您想创建一个带有嵌入式对等 Cache 实例的 Spring Boot 应用程序,其中您的应用程序将成为由 Pivotal GemFire 形成的集群(分布式系统)的服务器和对等成员,请从以下开始
Cache 应用程序@SpringBootApplication
@PeerCacheApplication
class ServerApplication { .. }
或者,您可以使用 @CacheServerApplication 注解而不是 @PeerCacheApplication 来创建一个嵌入式对等 Cache 实例以及一个运行在 localhost 上、监听默认缓存服务器端口 40404 的 CacheServer,如下所示
Cache 应用程序,带 CacheServer@SpringBootApplication
@CacheServerApplication
class ServerApplication { .. }
6.3. 客户端/服务器应用程序详细信息
客户端可以通过多种方式连接并与 Pivotal GemFire 集群中的服务器通信。最常见和推荐的方法是使用 Pivotal GemFire Locators。
缓存客户端可以连接到 Pivotal GemFire 集群中的一个或多个 Locators,而不是直接连接到 CacheServer。使用 Locators 而不是直接 CacheServer 连接的优势在于 Locators 提供有关客户端连接到的集群的元数据。此元数据包括哪些服务器包含感兴趣的数据或哪些服务器负载最少等信息。客户端 Pool 结合 Locator 还提供故障转移功能,以防 CacheServer 崩溃。通过在客户端 Pool 中启用 PARTITION Region (PR) 单跳功能,客户端可以直接路由到包含客户端请求和所需数据的服务器。 |
| 定位器也是集群中的对等成员。定位器实际上构成了 Pivotal GemFire 节点集群。也就是说,通过定位器连接的所有节点都是集群中的对等体,新成员使用定位器加入集群并查找其他成员。 |
默认情况下,Pivotal GemFire 在创建 ClientCache 实例时,会设置一个连接到运行在 localhost 上、监听端口 40404 的 CacheServer 的“DEFAULT”Pool。CacheServer 监听端口 40404,接受所有系统 NIC 上的连接。您无需做任何特殊操作即可使用客户端-服务器拓扑。只需使用 @CacheServerApplication 注解您的服务器端 Spring Boot 应用程序,并使用 @ClientCacheApplication 注解您的客户端 Spring Boot 应用程序,您就可以开始使用了。
如果您愿意,甚至可以使用 Gfsh 的 start server 命令启动服务器。您的 Spring Boot @ClientCacheApplication 仍然可以连接到服务器,无论它是如何启动的。但是,您可能更喜欢使用 Spring Data for Pivotal GemFire 方法配置和启动服务器,因为一个正确注解的 Spring Boot 应用程序类更加直观且易于调试。
作为应用程序开发人员,您无疑会希望自定义 Pivotal GemFire 设置的“DEFAULT”Pool,以便可能连接到一个或多个 Locator,如下例所示
ClientCache 应用程序使用 Locators@SpringBootApplication
@ClientCacheApplication(locators = {
@Locator(host = "boombox" port = 11235),
@Locator(host = "skullbox", port = 12480)
})
class ClientApplication { .. }
除了 locators 属性之外,@ClientCacheApplication 注解还有一个 servers 属性。servers 属性可用于指定一个或多个嵌套的 @Server 注解,这些注解允许缓存客户端在必要时直接连接到一个或多个服务器。
您可以使用 locators 或 servers 属性,但不能同时使用两者(这是由 Pivotal GemFire 强制执行的)。 |
您还可以配置额外的 Pool 实例(除了 Pivotal GemFire 在使用 @ClientCacheApplication 注解创建 ClientCache 实例时提供的“DEFAULT”Pool 之外),方法是使用 @EnablePool 和 @EnablePools 注解。
@EnablePools 是一个复合注解,它在单个类上聚合了多个嵌套的 @EnablePool 注解。Java 8 及更早版本不允许在单个类上声明多个相同类型的注解。 |
以下示例使用 @EnablePool 和 @EnablePools 注解
Pools 的基于 Spring 的 Pivotal GemFire ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication(logLevel = "info")
@EnablePool(name = "VenusPool", servers = @Server(host = "venus", port = 48484),
min-connections = 50, max-connections = 200, ping-internal = 15000,
prSingleHopEnabled = true, readTimeout = 20000, retryAttempts = 1,
subscription-enable = true)
@EnablePools(pools = {
@EnablePool(name = "SaturnPool", locators = @Locator(host="skullbox", port=20668),
subsription-enabled = true),
@EnablePool(name = "NeptunePool", severs = {
@Server(host = "saturn", port = 41414),
@Server(host = "neptune", port = 42424)
}, min-connections = 25))
})
class ClientApplication { .. }
name 属性是 @EnablePool 注解唯一必需的属性。正如我们稍后将看到的,name 属性的值对应于在 Spring 容器中创建的 Pool bean 的名称,以及用于引用相应配置属性的名称。它也是 Pivotal GemFire 注册和使用的 Pool 的名称。
同样,在服务器上,您可以配置客户端可以连接的多个 CacheServers,如下所示
CacheServers 的基于 Spring 的 Pivotal GemFire CacheServer 应用程序@SpringBootApplication
@CacheSeverApplication(logLevel = "info", autoStartup = true, maxConnections = 100)
@EnableCacheServer(name = "Venus", autoStartup = true,
hostnameForClients = "venus", port = 48484)
@EnableCacheServers(servers = {
@EnableCacheServer(name = "Saturn", hostnameForClients = "saturn", port = 41414),
@EnableCacheServer(name = "Neptune", hostnameForClients = "neptune", port = 42424)
})
class ServerApplication { .. }
与 @EnablePools 类似,@EnableCacheServers 是一个复合注解,用于在单个类上聚合多个 @EnableCacheServer 注解。同样,Java 8 及更早版本不允许在单个类上声明多个相同类型的注解。 |
细心的读者可能已经注意到,在所有情况下,您都为所有主机名、端口和面向配置的注解属性指定了硬编码值。当应用程序被提升并部署到不同的环境(例如从 DEV 到 QA 到 STAGING 到 PROD)时,这并不理想。
下一节将介绍如何处理在运行时确定的动态配置。
6.4. 配置和引导定位器
除了 Pivotal GemFire Cache 应用程序,您还可以创建 Pivotal GemFire Locator 应用程序。
Pivotal GemFire Locator 是一个 JVM 进程,允许节点作为对等成员加入 Pivotal GemFire 集群。定位器还使客户端能够发现集群中的服务器。定位器向客户端提供元数据,以在集群成员之间均匀地平衡负载,并实现单跳数据访问操作以及其他功能。
关于定位器的完整讨论超出了本文档的范围。鼓励读者阅读 Pivotal GemFire 用户指南 以获取有关定位器及其在集群中作用的更多详细信息。
要配置和引导独立的 Locator 进程,请执行以下操作
@SpringBootApplication
@LocatorApplication(port = 12345)
class LocatorApplication { ... }
您可以在集群中启动多个定位器。唯一的要求是成员名称在集群中必须是唯一的。使用 @LocatorApplication 注解的 name 属性来相应地命名集群中的成员定位器。或者,您可以在 Spring Boot 的 application.properties 中设置 spring.data.gemfire.locator.name 属性。
此外,如果您在同一台机器上 fork 多个定位器,则必须确保每个定位器都在唯一的端口上启动。设置 port 注解属性或 spring.data.gemfire.locator.port 属性。
然后,您可以在集群中启动 1 个或多个由 Locator(或 Locators)加入的 Pivotal GemFire 对等缓存成员,这些成员也使用 Spring 配置和引导,如下所示
CacheServer 应用程序由 localhost 上的 Locator 加入,端口 12345@SpringBootApplication
@CacheServerApplication(locators = "localhost[12345]")
class ServerApplication { ... }
同样,您可以启动任意数量的 ServerApplication 类,由我们上面的 Locator 加入。您只需要确保成员名称是唯一的。
@LocatorApplication 用于配置和引导独立的 Pivotal GemFire Locator 应用程序进程。此进程只能是定位器,不能是其他任何东西。如果您尝试使用缓存实例启动定位器,SDG 将会抛出错误。
如果您想同时启动缓存实例和嵌入式定位器,则应改用 @EnableLocator 注解。
在开发过程中启动嵌入式定位器很方便。但是,强烈建议您在生产环境中运行独立的定位器进程以实现高可用性。如果集群中的所有定位器都崩溃,则集群将保持完整,但是,没有新成员能够加入集群,这对于线性横向扩展以满足需求非常重要。
有关详细信息,请参阅配置嵌入式定位器部分。
6.5. 使用 Configurers 进行运行时配置
在设计基于注解的配置模型时的另一个目标是保留注解属性的类型安全。例如,如果配置属性可以表示为 int(例如端口号),则属性的类型应为 int。
不幸的是,这不利于运行时的动态和可解析配置。
Spring 的一个优点是能够在 Spring 容器中配置 bean 时,在配置元数据的属性或属性中使用属性占位符和 SpEL 表达式。但是,这将要求所有注解属性都为 String 类型,从而放弃类型安全,这是不可取的。
因此,Spring Data for Pivotal GemFire 借鉴了 Spring 中另一个常用模式:Configurers。Spring Web MVC 中提供了许多不同的 Configurer 接口,包括 org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer。
Configurers 设计模式使应用程序开发人员能够在启动时接收回调以自定义组件或 bean 的配置。框架回调用户提供的代码以在运行时调整配置。此模式的一个更常见用途是根据应用程序的运行时环境提供条件配置。
Spring Data for Pivotal GemFire 提供了几个 Configurer 回调接口,用于在注解创建的 Spring 管理的 bean 初始化之前,在运行时自定义基于注解的配置元数据的不同方面
-
CacheServerConfigurer -
ClientCacheConfigurer -
ContinuousQueryListenerContainerConfigurer -
DiskStoreConfigurer -
IndexConfigurer -
PeerCacheConfigurer -
PoolConfigurer -
RegionConfigurer -
GatewayReceiverConfigurer -
GatewaySenderConfigurer
例如,您可以使用 CacheServerConfigurer 和 ClientCacheConfigurer 分别自定义 Spring Boot CacheServer 和 ClientCache 应用程序使用的端口号。
考虑以下服务器应用程序示例
CacheServerConfigurer 自定义 Spring Boot CacheServer 应用程序@SpringBootApplication
@CacheServerApplication(name = "SpringServerApplication")
class ServerApplication {
@Bean
CacheServerConfigurer cacheServerPortConfigurer(
@Value("${gemfire.cache.server.host:localhost}") String cacheServerHost
@Value("${gemfire.cache.server.port:40404}") int cacheServerPort) {
return (beanName, cacheServerFactoryBean) -> {
cacheServerFactoryBean.setBindAddress(cacheServerHost);
cacheServerFactoryBean.setHostnameForClients(cacheServerHost);
cacheServerFactoryBean.setPort(cacheServerPort);
};
}
}
接下来,考虑以下客户端应用程序示例
ClientCacheConfigurer 自定义 Spring Boot ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
class ClientApplication {
@Bean
ClientCacheConfigurer clientCachePoolPortConfigurer(
@Value("${gemfire.cache.server.host:localhost}") String cacheServerHost
@Value("${gemfire.cache.server.port:40404}") int cacheServerPort) {
return (beanName, clientCacheFactoryBean) ->
clientCacheFactoryBean.setServers(Collections.singletonList(
new ConnectionEndpoint(cacheServerHost, cacheServerPort)));
}
}
通过使用提供的 Configurers,您可以在启动期间接收回调,以在运行时进一步自定义关联注解启用的配置。
此外,当 Configurer 在 Spring 容器中声明为 bean 时,bean 定义可以利用其他 Spring 容器特性,例如通过在工厂方法参数上使用 @Value 注解来使用属性占位符和 SpEL 表达式,等等。
Spring Data for Pivotal GemFire 提供的所有 Configurers 在回调中获取两个信息:由注解在 Spring 容器中创建的 bean 的名称,以及注解用于创建和配置 Pivotal GemFire 组件的 FactoryBean 的引用(例如,使用 ClientCacheFactoryBean 创建和配置 ClientCache 实例)。
SDG FactoryBeans 是 SDG 公共 API 的一部分,如果未提供这种新的基于注解的配置模型,您将在 Spring 的基于 Java 的容器配置中使用它们。实际上,注解本身正在使用这些相同的 FactoryBeans 进行配置。因此,本质上,注解是一个外观,为方便起见提供了一个额外的抽象层。 |
鉴于 Configurer 可以像任何其他 POJO 一样声明为常规 bean 定义,您可以组合不同的 Spring 配置选项,例如将 Spring Profile 与使用属性占位符和 SpEL 表达式的 Conditions 结合使用。这些以及其他巧妙的功能使您能够创建更复杂和灵活的配置。
然而,Configurers 并不是唯一的选择。
6.6. 使用 Properties 进行运行时配置
除了 Configurers 之外,基于注解的配置模型中的每个注解属性都与相应的配置属性(以 spring.data.gemfire. 为前缀)相关联,该属性可以在 Spring Boot 的 application.properties 文件中声明。
在前述示例的基础上,客户端的 application.properties 文件将定义以下属性集
application.propertiesspring.data.gemfire.cache.log-level=info
spring.data.gemfire.pool.Venus.servers=venus[48484]
spring.data.gemfire.pool.Venus.max-connections=200
spring.data.gemfire.pool.Venus.min-connections=50
spring.data.gemfire.pool.Venus.ping-interval=15000
spring.data.gemfire.pool.Venus.pr-single-hop-enabled=true
spring.data.gemfire.pool.Venus.read-timeout=20000
spring.data.gemfire.pool.Venus.subscription-enabled=true
spring.data.gemfire.pool.Saturn.locators=skullbox[20668]
spring.data.gemfire.pool.Saturn.subscription-enabled=true
spring.data.gemfire.pool.Neptune.servers=saturn[41414],neptune[42424]
spring.data.gemfire.pool.Neptune.min-connections=25
相应的服务器的 application.properties 文件将定义以下属性
application.propertiesspring.data.gemfire.cache.log-level=info
spring.data.gemfire.cache.server.port=40404
spring.data.gemfire.cache.server.Venus.port=43434
spring.data.gemfire.cache.server.Saturn.port=41414
spring.data.gemfire.cache.server.Neptune.port=41414
然后,您可以将 @ClientCacheApplication 类简化为以下内容
@ClientCacheApplication 类@SpringBootApplication
@ClientCacheApplication
@EnablePools(pools = {
@EnablePool(name = "Venus"),
@EnablePool(name = "Saturn"),
@EnablePool(name = "Neptune")
})
class ClientApplication { .. }
同样,@CacheServerApplication 类变为以下内容
@CacheServerApplication 类@SpringBootApplication
@CacheServerApplication(name = "SpringServerApplication")
@EnableCacheServers(servers = {
@EnableCacheServer(name = "Venus"),
@EnableCacheServer(name = "Saturn"),
@EnableCacheServer(name = "Neptune")
})
class ServerApplication { .. }
前面的示例说明了为什么“命名”基于注解的 bean 很重要(除了在某些情况下是必需的)。这样做使得可以从 XML、属性和 Java 中引用 Spring 容器中的 bean。甚至可以将注解定义的 bean 注入应用程序类,无论出于何种目的,如下例所示
@Component
class MyApplicationComponent {
@Resource(name = "Saturn")
CacheServer saturnCacheServer;
...
}
同样,命名注解定义的 bean 允许您编写一个 Configurer 来自定义特定的“命名”bean,因为 beanName 是传递给回调的两个参数之一。
通常,关联的注解属性属性有两种形式:“命名”属性和“未命名”属性。
以下示例显示了这种安排
spring.data.gemfire.cache.server.bind-address=10.105.20.1
spring.data.gemfire.cache.server.Venus.bind-address=10.105.20.2
spring.data.gemfire.cache.server.Saturn...
spring.data.gemfire.cache.server.Neptune...
虽然上面有三个命名的 CacheServers,但还有一个未命名的 CacheServer 属性,为任何未指定的属性值(甚至对于“命名”的 CacheServers)提供默认值。因此,虽然“Venus”设置并覆盖了自己的 bind-address,但“Saturn”和“Neptune”继承了“未命名”的 spring.data.gemfire.cache.server.bind-address 属性。
请参阅注解的 Javadoc,了解哪些注解属性支持基于属性的配置,以及它们是否支持优先于默认“未命名”属性的“命名”属性。
6.6.1. Properties 的 Properties
按照通常的 Spring 方式,您甚至可以用其他 Properties 来表达 Properties,无论是通过以下示例在 application.properties 文件中设置嵌套属性
spring.data.gemfire.cache.server.port=${gemfire.cache.server.port:40404}
以下示例显示了在 Java 中设置嵌套属性
@Bean
CacheServerConfigurer cacheServerPortConfigurer(
@Value("${gemfire.cache.server.port:${some.other.property:40404}}")
int cacheServerPort) {
...
}
| 属性占位符嵌套可以任意深入。 |
6.7. 配置嵌入式服务
Pivotal GemFire 提供了根据用例启动应用程序所需的许多不同嵌入式服务的能力。
6.7.1. 配置嵌入式定位器
如前所述,Pivotal GemFire Locators 用于客户端连接和查找集群中的服务器。此外,加入现有集群的新成员使用 Locators 来查找它们的对等体。
对于应用程序开发人员来说,在开发 Spring Boot 和 Spring Data for Pivotal GemFire 应用程序时,启动一个由两三个 Pivotal GemFire 服务器组成的小型集群通常很方便。除了启动一个单独的 Locator 进程之外,您还可以使用 @EnableLocator 注解您的 Spring Boot @CacheServerApplication 类,如下所示
CacheServer 应用程序运行嵌入式 Locator@SpringBootApplication
@CacheServerApplication
@EnableLocator
class ServerApplication { .. }
@EnableLocator 注解在运行在 localhost 上,监听默认 Locator 端口 10334 的 Spring Pivotal GemFire CacheServer 应用程序中启动一个嵌入式 Locator。您可以使用相应的注解属性来自定义嵌入式 Locator 绑定的 host(绑定地址)和 port。
或者,您可以通过在 application.properties 中设置相应的 spring.data.gemfire.locator.host 和 spring.data.gemfire.locator.port 属性来设置 @EnableLocator 属性。
然后,您可以通过以下方式连接到此 Locator 来启动其他启用 Spring Boot @CacheServerApplication 的应用程序
CacheServer 应用程序连接到 Locator@SpringBootApplication
@CacheServerApplication(locators = "localhost[10334]")
class ServerApplication { .. }
您甚至可以将前面显示的两个应用程序类组合成一个类,并使用 IDE 创建不同的运行配置文件配置,通过使用 Java 系统属性启动同一类的不同实例,并进行稍微修改的配置,如下所示
CacheServer 应用程序运行嵌入式 Locator 并连接到 Locator@SpringBootApplication
@CacheServerApplication(locators = "localhost[10334]")
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class);
}
@EnableLocator
@Profile("embedded-locator")
static class Configuration { }
}
然后,对于每个运行配置文件,您可以设置和更改以下系统属性
spring.data.gemfire.name=SpringCacheServerOne
spring.data.gemfire.cache.server.port=41414
spring.profiles.active=embedded-locator
ServerApplication 类的运行配置文件中只有 1 个应设置 -Dspring.profiles.active=embedded-locator Java 系统属性。然后,您可以为每个其他运行配置文件更改 ..name 和 ..cache.server.port,并在本地系统上运行一个由 Pivotal GemFire 服务器组成的小型集群(分布式系统)。
@EnableLocator 注解仅用于开发时注解,而不是应用程序开发人员在生产环境中使用。我们强烈建议将 Locator 作为独立的、独立的进程在集群中运行。 |
有关 Pivotal GemFire Locators 如何工作的更多详细信息,请参见此处。
6.7.2. 配置嵌入式管理器
Pivotal GemFire 管理器是集群中的另一个对等成员或节点,负责集群“管理”。管理涉及创建 Regions、Indexes、DiskStores 等,以及监控集群组件的运行时操作和行为。
管理器允许启用 JMX 的客户端(例如 Gfsh shell 工具)连接到管理器以管理集群。还可以使用 JDK 提供的工具(如 JConsole 或 JVisualVM)连接到管理器,因为这些工具也都是启用 JMX 的客户端。
也许您还想将前面显示的 Spring @CacheServerApplication 启用为管理器。为此,请使用 @EnableManager 注解您的 Spring @Configuration 或 @SpringBootApplication 类。
默认情况下,管理器绑定到 localhost,监听默认管理器端口 1099。管理器的多个方面可以通过注解属性或相应属性进行配置。
以下示例显示了如何在 Java 中创建嵌入式管理器
CacheServer 应用程序@SpringBootApplication
@CacheServerApplication(locators = "localhost[10334]")
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class);
}
@EnableLocator
@EnableManager
@Profile("embedded-locator-manager")
static class Configuration { }
}
使用上述类,您甚至可以使用 Gfsh 连接到小型集群并对其进行管理,如下所示
$ gfsh
_________________________ __
/ _____/ ______/ ______/ /____/ /
/ / __/ /___ /_____ / _____ /
/ /__/ / ____/ _____/ / / / /
/______/_/ /______/_/ /_/ 1.2.1
Monitor and Manage {data-store-name}
gfsh>connect
Connecting to Locator at [host=localhost, port=10334] ..
Connecting to Manager at [host=10.99.199.5, port=1099] ..
Successfully connected to: [host=10.99.199.5, port=1099]
gfsh>list members
Name | Id
---------------------- | ----------------------------------------------------
SpringCacheServerOne | 10.99.199.5(SpringCacheServerOne:14842)<ec><v0>:1024
SpringCacheServerTwo | 10.99.199.5(SpringCacheServerTwo:14844)<v1>:1025
SpringCacheServerThree | 10.99.199.5(SpringCacheServerThree:14846)<v2>:1026
因为我们也启用了嵌入式定位器,所以我们可以通过定位器间接连接到管理器。定位器允许 JMX 客户端连接并查找集群中的管理器。如果不存在,定位器会承担管理器的角色。但是,如果不存在定位器,我们需要使用以下方法直接连接到管理器
connect 命令直接连接到管理器gfsh>connect --jmx-manager=localhost[1099]
与 @EnableLocator 注解类似,@EnableManager 注解也仅用于开发时注解,而不是应用程序开发人员在生产环境中使用。我们强烈建议管理器(如定位器)在集群中作为独立的、独立的专用进程运行。 |
有关 Pivotal GemFire 管理和监控的更多详细信息,请参见此处。
6.7.3. 配置嵌入式 HTTP 服务器
Pivotal GemFire 还能够运行嵌入式 HTTP 服务器。当前的实现由 Eclipse Jetty 提供支持。
嵌入式 HTTP 服务器用于托管 Pivotal GemFire 的管理 (Admin) REST API(非公开 API)、开发人员 REST API 和 Pulse 监控 Web 应用程序。
但是,要使用这些 Pivotal GemFire 提供的 Web 应用程序中的任何一个,您必须在系统上完整安装 Pivotal GemFire,并且必须将 GEODE_HOME 环境变量设置为您的安装目录。
要启用嵌入式 HTTP 服务器,请将 @EnableHttpService 注解添加到任何 @PeerCacheApplication 或 @CacheServerApplication 注解类,如下所示
CacheServer 应用程序运行嵌入式 HTTP 服务器@SpringBootApplication
@CacheServerApplication
@EnableHttpService
public class ServerApplication { .. }
默认情况下,嵌入式 HTTP 服务器监听端口 7070 以处理 HTTP 客户端请求。当然,您可以根据需要使用注解属性或相应的配置属性来调整端口。
有关 HTTP 支持和提供服务的更多详细信息,请参阅前面的链接。
6.7.4. 配置嵌入式 Memcached 服务器 (Gemcached)
Pivotal GemFire 还实现了 Memcached 协议,能够为 Memcached 客户端提供服务。也就是说,Memcached 客户端可以连接到 Pivotal GemFire 集群并执行 Memcached 操作,就好像集群中的 Pivotal GemFire 服务器是真正的 Memcached 服务器一样。
要启用嵌入式 Memcached 服务,请将 @EnableMemcachedServer 注解添加到任何 @PeerCacheApplication 或 @CacheServerApplication 注解类,如下所示
CacheServer 应用程序运行嵌入式 Memcached 服务器@SpringBootApplication
@CacheServerApplication
@EnabledMemcachedServer
public class ServerApplication { .. }
有关 Pivotal GemFire 的 Memcached 服务(称为“Gemcached”)的更多详细信息,请参见此处。
6.7.5. 配置嵌入式 Redis 服务器
Pivotal GemFire 还实现了 Redis 服务器协议,该协议允许 Redis 客户端连接并与 Pivotal GemFire 服务器集群通信以发出 Redis 命令。截至撰写本文时,Pivotal GemFire 中的 Redis 服务器协议支持仍处于实验阶段。
要启用嵌入式 Redis 服务,请将 @EnableRedisServer 注解添加到任何 @PeerCacheApplication 或 @CacheServerApplication 注解类,如下所示
CacheServer 应用程序运行嵌入式 Redis 服务器@SpringBootApplication
@CacheServerApplication
@EnableRedisServer
public class ServerApplication { .. }
您必须在 Spring [Boot] 应用程序的类路径上显式声明 org.apache.geode:geode-redis 模块。 |
有关 Pivotal GemFire 的 Redis 适配器的更多详细信息,请参见此处。
6.8. 配置日志记录
通常,为了准确了解 Pivotal GemFire 正在做什么以及何时执行,需要增加日志记录级别。
要启用日志记录,请使用 @EnableLogging 注解您的应用程序类并设置相应的属性或关联属性,如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableLogging(logLevel="info", logFile="/absolute/file/system/path/to/application.log)
public class ClientApplication { .. }
虽然可以使用所有基于缓存的应用程序注解指定 logLevel 属性(例如,@ClientCacheApplication(logLevel="info")),但使用 @EnableLogging 注解更容易自定义日志记录行为。
此外,您可以通过在 application.properties 中设置 spring.data.gemfire.logging.level 属性来配置 log-level。
有关详细信息,请参阅 @EnableLogging 注解 Javadoc。
6.9. 配置统计信息
为了更深入地了解 Pivotal GemFire 的运行时情况,您可以启用统计信息。收集统计数据有助于在出现复杂问题(通常是分布式性质且时序是关键因素)时进行系统分析和故障排除。
启用统计信息后,您可以使用 Pivotal GemFire 的 VSD (Visual Statistics Display) 工具来分析收集到的统计数据。
要启用统计信息,请使用 @EnableStatistics 注解您的应用程序类,如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableStatistics
public class ClientApplication { .. }
在评估性能时,在服务器上启用统计信息特别有价值。为此,请使用 @EnableStatistics 注解您的 @PeerCacheApplication 或 @CacheServerApplication 类。
您可以使用 @EnableStatistics 注解属性或关联属性来自定义统计数据收集过程。
有关详细信息,请参阅 @EnableStatistics 注解 Javadoc。
有关 Pivotal GemFire 统计信息的更多详细信息,请参见此处。
6.10. 配置 PDX
Pivotal GemFire 最强大的功能之一是 PDX 序列化。虽然本文档不完全讨论 PDX,但使用 PDX 进行序列化是 Java 序列化的更好替代方案,具有以下优点
-
PDX 使用集中式类型注册表来使对象的序列化字节更紧凑。
-
PDX 是一种中立的序列化格式,允许 Java 和 Native 客户端对相同的数据集进行操作。
-
PDX 支持版本控制,允许添加或删除对象字段,而不会影响使用 PDX 序列化对象的旧版本或新版本的现有应用程序,且不会丢失数据。
-
PDX 允许在 OQL 查询投影和谓词中单独访问对象字段,而无需首先反序列化对象。
通常,在正常分发和复制过程中,以及数据溢出或持久化到磁盘时,只要数据在客户端和服务器之间或集群中的对等体之间传输,Pivotal GemFire 就需要序列化。
启用 PDX 序列化比修改所有应用程序域对象类型以实现 java.io.Serializable 简单得多,特别是当对应用程序域模型施加此类限制可能不理想或您无法控制要序列化的对象时,在使用第三方库(例如,考虑具有 Coordinate 类型的地理空间 API)时尤其如此。
要启用 PDX,请使用 @EnablePdx 注解您的应用程序类,如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnablePdx
public class ClientApplication { .. }
通常,应用程序的域对象类型要么实现 org.apache.geode.pdx.PdxSerializable 接口,要么您可以实现并注册 org.apache.geode.pdx.PdxSerializer 接口的非侵入式实现来处理所有需要序列化的应用程序域对象类型。
不幸的是,Pivotal GemFire 只允许注册一个 PdxSerializer,这意味着所有应用程序域对象类型都需要由单个 PdxSerializer 实例处理。然而,这是一种严重的非模式和不可维护的做法。
尽管 Pivotal GemFire 只能注册一个 PdxSerializer 实例,但为每个应用程序域对象类型创建单个 PdxSerializer 实现是有意义的。
通过使用 组合软件设计模式,您可以提供 PdxSerializer 接口的实现,该实现聚合了所有应用程序域对象类型特定的 PdxSerializer 实例,但作为单个 PdxSerializer 实例并进行注册。
您可以在 Spring 容器中将此复合 PdxSerializer 声明为托管 bean,并使用 serializerBeanName 属性在 @EnablePdx 注解中通过其 bean 名称引用此复合 PdxSerializer。Spring Data for Pivotal GemFire 将代表您负责将其注册到 Pivotal GemFire。
以下示例显示了如何创建自定义复合 PdxSerializer
ClientCache 应用程序,使用自定义复合 PdxSerializer@SpringBootApplication
@ClientCacheApplication
@EnablePdx(serializerBeanName = "compositePdxSerializer")
public class ClientApplication {
@Bean
PdxSerializer compositePdxSerializer() {
return new CompositePdxSerializerBuilder()...
}
}
还可以将 Pivotal GemFire 的 org.apache.geode.pdx.ReflectionBasedAutoSerializer 声明为 Spring 上下文中的 bean 定义。
或者,您应该使用 Spring Data for Pivotal GemFire 更强大的 org.springframework.data.gemfire.mapping.MappingPdxSerializer,它使用 Spring Data 映射元数据和基础设施应用于序列化过程,以实现比仅反射更高效的处理。
PDX 的许多其他方面和功能可以通过 @EnablePdx 注解属性或关联的配置属性进行调整。
有关详细信息,请参阅 @EnablePdx 注解 Javadoc。
6.11. 配置 Pivotal GemFire 属性
虽然许多 gemfire.properties 已在 SDG 基于注解的配置模型中方便地封装和抽象化,但较不常用的 Pivotal GemFire 属性仍然可以通过 @EnableGemFireProperties 注解访问。
在应用程序类上使用 @EnableGemFireProperties 注解很方便,是创建 gemfire.properties 文件或在启动应用程序时在命令行上将 Pivotal GemFire 属性设置为 Java 系统属性的不错替代方案。
我们建议在将应用程序部署到生产环境时将这些 Pivotal GemFire 属性设置在 gemfire.properties 文件中。但是,在开发阶段,为了原型、调试和测试目的,单独设置这些属性可能很方便。 |
一些不常用的 Pivotal GemFire 属性示例包括但不限于:ack-wait-threshold、disable-tcp、socket-buffer-size 等。
要单独设置任何 Pivotal GemFire 属性,请使用 @EnableGemFireProperties 注解您的应用程序类,并使用相应的属性设置您想要更改的 Pivotal GemFire 属性(与 Pivotal GemFire 设置的默认值不同),如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableGemFireProperties(conflateEvents = true, socketBufferSize = 16384)
public class ClientApplication { .. }
请记住,某些 Pivotal GemFire 属性是客户端特定的(例如 conflateEvents),而另一些是服务器特定的(例如 distributedSystemId、enableNetworkPartitionDetection、enforceUniqueHost、memberTimeout、redundancyZone 等)。
有关 Pivotal GemFire 属性的更多详细信息,请参见此处。
6.12. 配置区域
到目前为止,除了 PDX,我们的讨论都集中在配置 Pivotal GemFire 的更多管理功能:创建缓存实例、启动嵌入式服务、启用日志记录和统计信息、配置 PDX,以及使用 gemfire.properties 来影响低级配置和行为。虽然所有这些配置选项都很重要,但它们都与您的应用程序没有直接关系。换句话说,我们仍然需要一个地方来存储我们的应用程序数据并使其普遍可用和可访问。
以前,Spring Data for Pivotal GemFire 用户需要通过编写非常详细的 Spring 配置元数据来显式定义和声明其应用程序用于存储数据的区域,无论是使用 SDG API 中的 FactoryBeans 结合 Spring 的基于 Java 的容器配置还是使用XML。
以下示例演示如何在 Java 中配置 Region bean
@Configuration
class GemFireConfiguration {
@Bean("Example")
PartitionedRegionFactoryBean exampleRegion(GemFireCache gemfireCache) {
PartitionedRegionFactoryBean<Long, Example> exampleRegion =
new PartitionedRegionFactoryBean<>();
exampleRegion.setCache(gemfireCache);
exampleRegion.setClose(false);
exampleRegion.setPersistent(true);
return exampleRegion;
}
...
}
以下示例演示如何在 XML 中配置相同的 Region bean
<gfe:partitioned-region id="exampleRegion" name="Example" persistent="true">
...
</gfe:partitioned-region>
虽然 Java 或 XML 配置都不是很复杂,但任何一种都可能很繁琐,特别是如果应用程序需要大量区域。许多基于关系数据库的应用程序可以有数百甚至数千个表。
手动定义和声明所有这些区域将是繁琐且容易出错的。现在,有一种更好的方法。
现在,您可以根据应用程序域对象(实体)本身定义和配置区域。除非您需要更精细的控制,否则不再需要显式定义 Spring 配置元数据中的 Region bean 定义。
为了简化 Region 创建,Spring Data for Pivotal GemFire 将 Spring Data Repositories 的使用与使用新的 @EnableEntityDefinedRegions 注解的基于注解的配置的表达能力结合起来。
| 大多数 Spring Data 应用程序开发人员应该已经熟悉 Spring Data Repository 抽象以及 Spring Data for Pivotal GemFire 的实现/扩展,后者经过专门定制以优化 Pivotal GemFire 的数据访问操作。 |
首先,应用程序开发人员通过定义应用程序的域对象(实体)开始,如下所示
@Region("Books")
class Book {
@Id
private ISBN isbn;
private Author author;
private Category category;
private LocalDate releaseDate;
private Publisher publisher;
private String title;
}
接下来,您通过扩展 Spring Data Commons org.springframework.data.repository.CrudRepository 接口来定义 Books 的基本存储库,如下所示
interface BookRepository extends CrudRepository<Book, ISBN> { .. }
org.springframe.data.repository.CrudRepository 是一个数据访问对象 (DAO),提供基本的数据访问操作 (CRUD) 以及对简单查询(例如 findById(..))的支持。您可以通过在存储库接口上声明查询方法来定义额外的、更复杂的查询(例如,List<BooK> findByAuthor(Author author);)。
在底层,Spring Data for Pivotal GemFire 在 Spring 容器引导时提供应用程序存储库接口的实现。只要您遵循约定,SDG 甚至会实现您定义的查询方法。
现在,当您定义 Book 类时,您还通过在实体的类型上声明 Spring Data for Pivotal GemFire 映射注解 @Region 来指定 Book 实例映射(存储)到的 Region。当然,如果存储库接口(在本例中为 BookRepository)的类型参数中引用的实体类型(在本例中为 Book)没有用 @Region 注解,则名称将从实体类型的简单类名(在本例中也为 Book)派生。
Spring Data for Pivotal GemFire 使用映射上下文(其中包含应用程序中定义的所有实体的映射元数据)来确定运行时需要的所有 Region。
要启用和使用此功能,请使用 @EnableEntityDefinedRegions 注解应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableEntityDefinedRegions(basePackages = "example.app.domain")
@EnableGemfireRepositories(basePackages = "example.app.repo")
class ClientApplication { .. }
从实体类创建区域在应用程序中使用 Spring Data Repositories 时最有用。Spring Data for Pivotal GemFire 的 Repository 支持通过 @EnableGemfireRepositories 注解启用,如前面的示例所示。 |
目前,只有显式使用 @Region 注解的实体类才会被扫描到并创建 Region。如果实体类没有显式映射 @Region,则不会创建 Region。 |
默认情况下,@EnableEntityDefinedRegions 注解从声明 @EnableEntityDefinedRegions 注解的配置类的包开始递归扫描实体类。
但是,通常可以通过使用包含应用程序实体类的包名设置 basePackages 属性来限制扫描期间的搜索。
或者,您可以使用更类型安全的 basePackageClasses 属性来指定要扫描的包,方法是将属性设置为包中的实体类型(该包包含实体类),或者使用专门用于识别要扫描的包的非实体占位符类。
以下示例演示如何指定要扫描的实体类型
@SpringBootApplication
@ClientCacheApplication
@EnableGemfireRepositories
@EnableEntityDefinedRegions(basePackageClasses = {
example.app.books.domain.Book.class,
example.app.customers.domain.Customer.class
})
class ClientApplication { .. }
除了指定扫描的起始位置外,像 Spring 的 @ComponentScan 注解一样,您还可以指定 include 和 exclude 过滤器,并具有 org.springframework.context.annotation.ComponentScan.Filter 注解的所有相同语义。
有关详细信息,请参阅 @EnableEntityDefinedRegions 注解 Javadoc。
6.12.1. 配置特定类型的区域
Pivotal GemFire 支持许多不同类型的区域。每种类型对应于区域的DataPolicy,它决定了区域中的数据将如何管理(即,分发、复制等)。
其他配置设置(例如区域的 scope)也会影响数据的管理方式。有关详细信息,请参阅 Pivotal GemFire 用户指南中的 “存储和分发选项”。 |
当您使用通用 @Region 映射注解标注您的应用程序域对象类型时,Spring Data for Pivotal GemFire 会决定要创建的 Region 类型。SDG 的默认策略在确定要创建的 Region 类型时会考虑缓存类型。
例如,如果您使用 @ClientCacheApplication 注解将应用程序声明为 ClientCache,则 SDG 默认创建客户端 PROXY Region。或者,如果您使用 @PeerCacheApplication 或 @CacheServerApplication 注解将应用程序声明为对等 Cache,则 SDG 默认创建服务器 PARTITION Region。
当然,您总可以在必要时覆盖默认值。为了覆盖 Spring Data for Pivotal GemFire 应用的默认值,引入了四个新的 Region 映射注解
-
@ClientRegion -
@LocalRegion -
@PartitionRegion -
@ReplicateRegion
@ClientRegion 映射注解特定于客户端应用程序。上面列出的所有其他区域映射注解只能在具有嵌入式对等 Cache 的服务器应用程序中使用。
有时,客户端应用程序需要创建和使用本地专用区域,可能用于聚合来自其他区域的数据,以便在本地分析数据并执行应用程序代表用户执行的某些功能。在这种情况下,除非其他应用程序需要访问结果,否则数据不需要分发回服务器。此区域甚至可以是临时的,使用后可以丢弃,这可以通过区域本身的空闲超时 (TTI) 和生存时间 (TTL) 过期策略来实现。(有关过期策略的更多信息,请参见“配置过期”)。
| 区域级别的空闲超时(TTI)和生存时间(TTL)过期策略与入口级别的 TTI 和 TTL 过期策略是独立的且不同的。 |
在任何情况下,如果您想创建一个本地专用的客户端 Region,其中数据不会分发回服务器上同名的相应 Region,您可以声明 @ClientRegion 映射注解并将 shortcut 属性设置为 ClientRegionShortcut.LOCAL,如下所示
ClientCache 应用程序,带有一个本地专用客户端 Region@ClientRegion(shortcut = ClientRegionShortcut.LOCAL)
class ClientLocalEntityType { .. }
所有 Region 类型特定注解都提供额外的属性,这些属性既在 Region 类型之间通用,也特定于该 Region 类型。例如,PartitionRegion 注解中的 collocatedWith 和 redundantCopies 属性仅适用于服务器端 PARTITION Region。
有关 Pivotal GemFire Region 类型的更多详细信息,请参见此处。
6.12.2. 配置集群定义的区域
除了 @EnableEntityDefinedRegions 注解之外,Spring Data for Pivotal GemFire 还提供了相反的注解 @EnableClusterDefinedRegions。您可以根据应用程序用例 (UC) 和需求定义和驱动实体类来构建区域(最常见和逻辑的方法),或者,您可以从集群中已定义的区域声明您的区域,您的 ClientCache 应用程序将连接到该集群。
这允许您使用服务器集群作为数据定义的主要来源来集中配置,并确保集群的所有客户端应用程序都具有一致的配置。这在云管理环境中快速扩展大量相同客户端应用程序实例以处理增加的负载时特别有用。
这个想法是,不是由客户端应用程序驱动数据字典,而是用户使用 Pivotal GemFire 的 Gfsh CLI shell 工具定义区域。这有一个额外的好处,当向集群添加额外的对等体时,它们也将拥有并共享相同的配置,因为它被 Pivotal GemFire 的 Cluster Configuration Service 记住。
例如,用户可以在 Gfsh 中定义一个区域,如下所示
gfsh>create region --name=Books --type=PARTITION
Member | Status
--------- | --------------------------------------
ServerOne | Region "/Books" created on "ServerOne"
ServerTwo | Region "/Books" created on "ServerTwo"
gfsh>list regions
List of regions
---------------
Books
gfsh>describe region --name=/Books
..........................................................
Name : Books
Data Policy : partition
Hosting Members : ServerTwo
ServerOne
Non-Default Attributes Shared By Hosting Members
Type | Name | Value
------ | ----------- | ---------
Region | size | 0
| data-policy | PARTITION
使用 Pivotal GemFire 的 Cluster Configuration Service,添加到服务器集群中以处理增加的负载(在后端)的任何其他对等成员也将具有相同的配置,例如
gfsh>list members
Name | Id
--------- | ----------------------------------------------
Locator | 10.0.0.121(Locator:68173:locator)<ec><v0>:1024
ServerOne | 10.0.0.121(ServerOne:68242)<v3>:1025
ServerTwo | 10.0.0.121(ServerTwo:68372)<v4>:1026
gfsh>start server --name=ServerThree --log-level=config --server-port=41414
Starting a Geode Server in /Users/you/geode/cluster/ServerThree...
...
Server in /Users/you/geode/cluster/ServerThree... on 10.0.0.121[41414] as ServerThree is currently online.
Process ID: 68467
Uptime: 3 seconds
Geode Version: 1.2.1
Java Version: 1.8.0_152
Log File: /Users/you/geode/cluster/ServerThree/ServerThree.log
JVM Arguments: -Dgemfire.default.locators=10.0.0.121[10334]
-Dgemfire.use-cluster-configuration=true
-Dgemfire.start-dev-rest-api=false
-Dgemfire.log-level=config
-XX:OnOutOfMemoryError=kill -KILL %p
-Dgemfire.launcher.registerSignalHandlers=true
-Djava.awt.headless=true
-Dsun.rmi.dgc.server.gcInterval=9223372036854775806
Class-Path: /Users/you/geode/cluster/apache-geode-1.2.1/lib/geode-core-1.2.1.jar
:/Users/you/geode/cluster/apache-geode-1.2.1/lib/geode-dependencies.jar
gfsh>list members
Name | Id
----------- | ----------------------------------------------
Locator | 10.0.0.121(Locator:68173:locator)<ec><v0>:1024
ServerOne | 10.0.0.121(ServerOne:68242)<v3>:1025
ServerTwo | 10.0.0.121(ServerTwo:68372)<v4>:1026
ServerThree | 10.0.0.121(ServerThree:68467)<v5>:1027
gfsh>describe member --name=ServerThree
Name : ServerThree
Id : 10.0.0.121(ServerThree:68467)<v5>:1027
Host : 10.0.0.121
Regions : Books
PID : 68467
Groups :
Used Heap : 37M
Max Heap : 3641M
Working Dir : /Users/you/geode/cluster/ServerThree
Log file : /Users/you/geode/cluster/ServerThree/ServerThree.log
Locators : 10.0.0.121[10334]
Cache Server Information
Server Bind :
Server Port : 41414
Running : true
Client Connections : 0
如您所见,“ServerThree”现在拥有“Books”区域。如果任何或所有服务器都宕机,它们在重新启动时将拥有相同的配置以及“Books”区域。
在客户端,可能会启动许多图书商店客户端应用程序实例来处理图书商店在线服务中的图书。 “图书”区域可能是实现图书商店应用程序服务所需的众多不同区域之一。Spring Data for Pivotal GemFire 不必单独创建和配置每个区域,而是方便地允许从集群定义客户端应用程序区域,如下所示
@EnableClusterDefinedRegions 从集群定义客户端区域@ClientCacheApplication
@EnableClusterDefinedRegions
class BookStoreClientApplication {
public static void main(String[] args) {
....
}
...
}
@EnableClusterDefinedRegions 只能在客户端使用。 |
您可以使用 clientRegionShortcut 注解属性来控制在客户端创建的区域类型。默认情况下,会创建一个客户端 PROXY 区域。将 clientRegionShortcut 设置为 ClientRegionShortcut.CACHING_PROXY 以实现“近缓存”。此设置适用于从集群定义区域创建的所有客户端区域。如果您想控制从集群定义的区域创建的客户端区域的单个设置(如数据策略),那么您可以实现一个 RegionConfigurer,并根据区域名称使用自定义逻辑。 |
然后,在您的应用程序中使用“Books”区域就变得很简单了。您可以直接注入“Books”区域,如下所示
@org.springframework.stereotype.Repository
class BooksDataAccessObject {
@Resource(name = "Books")
private Region<ISBN, Book> books;
// implement CRUD and queries with the "Books" Region
}
或者,甚至可以根据应用程序域类型(实体)Book 定义一个 Spring Data Repository 定义,映射到“Books”区域,如下所示
interface BookRepository extends CrudRepository<Book, ISBN> {
...
}
然后,您可以将自定义 BooksDataAccessObject 或 BookRepository 注入到您的应用程序服务组件中,以执行所需的任何业务功能。
6.12.3. 配置驱逐
使用 Pivotal GemFire 管理数据是一个活跃的任务。通常需要进行调优,并且您必须结合使用多种功能(例如,驱逐和过期)才能有效地管理 Pivotal GemFire 中的内存数据。
鉴于 Pivotal GemFire 是一种内存数据网格 (IMDG),数据在内存中管理并分发到参与集群的其他节点,以最大限度地减少延迟、最大化吞吐量并确保数据高度可用。由于并非所有应用程序数据通常都能适应内存(即使是整个节点集群,更不用说单个节点),您可以通过向集群添加新节点来增加容量。这通常被称为线性横向扩展(而不是纵向扩展,纵向扩展意味着增加更多内存、更多 CPU、更多磁盘或更多网络带宽——基本上是更多所有系统资源以处理负载)。
尽管如此,即使有节点集群,通常也必须只将最重要的数据保留在内存中。内存不足,甚至接近满负荷,很少是好事。停止世界的 GC 或更糟糕的 OutOfMemoryErrors 会使您的应用程序戛然而止。
因此,为了帮助管理内存并保留最重要的数据,Pivotal GemFire 支持最近最少使用 (LRU) 驱逐。也就是说,Pivotal GemFire 使用最近最少使用算法根据区域条目上次访问的时间来驱逐它们。
要启用驱逐,请使用 @EnableEviction 注解应用程序类,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableEviction(policies = {
@EvictionPolicy(regionNames = "Books", action = EvictionActionType.INVALIDATE),
@EvictionPolicy(regionNames = { "Customers", "Orders" }, maximum = 90,
action = EvictionActionType.OVERFLOW_TO_DISK,
type = EvictonPolicyType.HEAP_PERCENTAGE)
})
class ServerApplication { .. }
驱逐策略通常在服务器的区域中设置。
如前所示,policies 属性可以指定一个或多个嵌套的 @EvictionPolicy 注解,每个注解都单独针对一个或多个需要应用驱逐策略的区域。
此外,您可以引用 Pivotal GemFire 的 org.apache.geode.cache.util.ObjectSizer 接口的自定义实现,该实现可以在 Spring 容器中定义为 bean,并使用 objectSizerName 属性通过名称引用。
ObjectSizer 允许您定义用于评估和确定存储在 Region 中的对象大小的条件。
有关驱逐配置选项的完整列表,请参阅 @EnableEviction 注解 Javadoc。
有关 Pivotal GemFire 驱逐的更多详细信息,请参见此处。
6.12.4. 配置过期
除了驱逐之外,过期也可以通过允许存储在区域中的条目过期来管理内存。Pivotal GemFire 支持生存时间 (TTL) 和空闲超时 (TTI) 条目过期策略。
Spring Data for Pivotal GemFire 基于注解的过期配置是基于 Spring Data for Pivotal GemFire 1.5 版本中添加的早期和现有条目过期注解支持。
本质上,Spring Data for Pivotal GemFire 的过期注解支持是基于 Pivotal GemFire 的 org.apache.geode.cache.CustomExpiry 接口的自定义实现。此 o.a.g.cache.CustomExpiry 实现检查存储在 Region 中的用户应用程序域对象是否存在类型级别的过期注解。
Spring Data for Pivotal GemFire 提供以下过期注解
-
Expiration -
IdleTimeoutExpiration -
TimeToLiveExpiration
应用程序域对象类型可以用一个或多个过期注解进行注解,如下所示
@Region("Books")
@TimeToLiveExpiration(timeout = 30000, action = "INVALIDATE")
class Book { .. }
要启用过期,请使用 @EnableExpiration 注解应用程序类,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableExpiration
class ServerApplication { .. }
除了应用程序域对象类型级别的过期策略之外,您还可以使用 @EnableExpiration 注解直接和单独地按区域配置过期策略,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableExpiration(policies = {
@ExpirationPolicy(regionNames = "Books", types = ExpirationType.TIME_TO_LIVE),
@ExpirationPolicy(regionNames = { "Customers", "Orders" }, timeout = 30000,
action = ExpirationActionType.LOCAL_DESTROY)
})
class ServerApplication { .. }
前面的示例为 Books、Customers 和 Orders 区域设置了过期策略。
过期策略通常在服务器的区域中设置。
有关过期配置选项的完整列表,请参阅 @EnableExpiration 注解 Javadoc。
有关 Pivotal GemFire 过期的更多详细信息,请参见此处。
6.12.5. 配置压缩
Pivotal GemFire 允许您使用可插拔的 Compressors(或不同的压缩编解码器)来压缩内存中的 Region 值。Pivotal GemFire 默认使用 Google 的 Snappy 压缩库。
要启用压缩,请使用 @EnableCompression 注解应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableCompression(compressorBeanName = "MyCompressor", regionNames = { "Customers", "Orders" })
class ClientApplication { .. }
compressorBeanName 和 regionNames 属性都不是必需的。 |
compressorBeanName 默认为 SnappyCompressor,启用 Pivotal GemFire 的 SnappyCompressor。
regionNames 属性是一个区域名称数组,用于指定启用压缩的区域。默认情况下,如果未显式设置 regionNames 属性,则所有区域都会压缩值。
或者,您可以在 application.properties 文件中使用 spring.data.gemfire.cache.compression.compressor-bean-name 和 spring.data.gemfire.cache.compression.region-names 属性来设置和配置这些 @EnableCompression 注解属性的值。 |
要使用 Pivotal GemFire 的区域压缩功能,您必须在应用程序的 pom.xml 文件(对于 Maven)或 build.gradle 文件(对于 Gradle)中包含 org.iq80.snappy:snappy 依赖项。这仅在您使用 Pivotal GemFire 对区域压缩的默认支持时才需要,该支持默认使用 SnappyCompressor。当然,如果您使用其他压缩库,则需要在应用程序的类路径中包含该压缩库的依赖项。此外,您需要实现 Pivotal GemFire 的 Compressor 接口以适应您选择的压缩库,将其定义为 Spring 压缩器中的 bean,并将 compressorBeanName 设置为此自定义 bean 定义。 |
有关详细信息,请参阅 @EnableCompression 注解 Javadoc。
有关 Pivotal GemFire 压缩的更多详细信息,请参见此处。
6.12.6. 配置堆外内存
另一种有效减轻 JVM 堆内存压力并最大程度减少 GC 活动的方法是使用 Pivotal GemFire 的堆外内存支持。
区域条目不是存储在 JVM 堆上,而是存储在系统的主要内存中。正如 Pivotal GemFire 用户指南中所解释的,堆外内存通常在存储的对象大小统一、大多小于 128K 且不需要频繁反序列化时效果最佳。
要启用堆外,请使用 @EnableOffHeap 注解应用程序类,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableOffHeap(memorySize = 8192m regionNames = { "Customers", "Orders" })
class ServerApplication { .. }
memorySize 属性是必需的。memorySize 属性的值指定 Region 可以使用的主内存量,单位为兆字节 (m) 或千兆字节 (g)。
regionNames 属性是一个区域名称数组,用于指定在主内存中存储条目的区域。默认情况下,如果未显式设置 regionNames 属性,则所有区域都使用主内存。
或者,您可以在 application.properties 文件中使用 spring.data.gemfire.cache.off-heap.memory-size 和 spring.data.gemfire.cache.off-heap.region-names 属性来设置和配置这些 @EnableOffHeap 注解属性的值。 |
有关详细信息,请参阅 @EnableOffHeap 注解 Javadoc。
6.12.7. 配置磁盘存储
或者,您可以配置区域以将数据持久化到磁盘。您还可以配置区域以在区域条目被驱逐时将数据溢出到磁盘。在这两种情况下,都需要 DiskStore 来持久化和/或溢出数据。当没有为具有持久性或溢出的区域配置显式 DiskStore 时,Pivotal GemFire 使用 DEFAULT DiskStore。
我们建议在将数据持久化和/或溢出到磁盘时定义特定于区域的 DiskStores。
Spring Data for Pivotal GemFire 提供了注解支持,通过使用 @EnableDiskStore 和 @EnableDiskStores 注解应用程序类来定义和创建应用程序区域 DiskStores。
@EnableDiskStores 是一个复合注解,用于聚合一个或多个 @EnableDiskStore 注解。 |
例如,图书信息可能主要由来自某些外部数据源(如亚马逊)的参考数据组成,而订单数据很可能具有事务性,并且是应用程序需要保留的东西(如果事务量足够高,甚至可能溢出到磁盘)——无论如何,任何图书出版商和作者都希望如此。
使用 @EnableDiskStore 注解,您可以定义和创建 DiskStore,如下所示
DiskStore 的 Spring 应用程序@SpringBootApplication
@PeerCacheApplication
@EnableDiskStore(name = "OrdersDiskStore", autoCompact = true, compactionThreshold = 70,
maxOplogSize = 512, diskDirectories = @DiskDiretory(location = "/absolute/path/to/order/disk/files"))
class ServerApplication { .. }
同样,可以使用复合注解 @EnableDiskStores 定义多个 DiskStore。
与 Spring Data for Pivotal GemFire 基于注解的配置模型中的其他注解一样,@EnableDiskStore 和 @EnableDiskStores 都具有许多属性以及相关的配置属性,用于在运行时自定义创建的 DiskStores。
此外,@EnableDiskStores 注解定义了适用于所有从与 @EnableDiskStores 注解本身组合的 @EnableDiskStore 注解创建的 DiskStores 的某些通用 DiskStore 属性。单个 DiskStore 配置会覆盖特定的全局设置,但 @EnableDiskStores 注解方便地定义了适用于注解聚合的所有 DiskStores 的通用配置属性。
Spring Data for Pivotal GemFire 还提供了 DiskStoreConfigurer 回调接口,该接口可以在 Java 配置中声明,并用于替代配置属性来在运行时自定义 DiskStore,如下例所示
@SpringBootApplication
@PeerCacheApplication
@EnableDiskStore(name = "OrdersDiskStore", autoCompact = true, compactionThreshold = 70,
maxOplogSize = 512, diskDirectories = @DiskDiretory(location = "/absolute/path/to/order/disk/files"))
class ServerApplication {
@Bean
DiskStoreConfigurer ordersDiskStoreDiretoryConfigurer(
@Value("${orders.disk.store.location}") String location) {
return (beanName, diskStoreFactoryBean) -> {
if ("OrdersDiskStore".equals(beanName) {
diskStoreFactoryBean.setDiskDirs(Collections.singletonList(new DiskDir(location));
}
}
}
}
有关可用属性以及相关配置属性的更多详细信息,请参阅 @EnableDiskStore 和 @EnableDiskStores 注解 Javadoc。
有关 Pivotal GemFire 区域持久性 和溢出(使用 DiskStores)的更多详细信息,请参见此处。
6.12.8. 配置索引
除非数据可以访问,否则将数据存储在区域中并没有多大用处。
除了 Region.get(key) 操作(特别是在预先知道键的情况下),通常通过对包含数据的区域执行查询来检索数据。使用 Pivotal GemFire,查询使用对象查询语言 (OQL) 编写,客户端希望访问的特定数据集在查询的谓词中表达(例如,SELECT * FROM /Books b WHERE b.author.name = 'Jon Doe')。
通常,没有索引的查询效率低下。在没有索引的情况下执行查询时,Pivotal GemFire 执行等同于全表扫描的操作。
Spring Data for Pivotal GemFire 使得在存储和访问数据的区域上创建索引变得容易。我们不再像以前那样通过 Spring 配置显式声明 Index bean 定义,我们可以在 Java 中创建 Index bean 定义,如下所示
@Bean("BooksIsbnIndex")
IndexFactoryBean bookIsbnIndex(GemFireCache gemfireCache) {
IndexFactoryBean bookIsbnIndex = new IndexFactoryBean();
bookIsbnIndex.setCache(gemfireCache);
bookIsbnIndex.setName("BookIsbnIndex");
bookIsbnIndex.setExpression("isbn");
bookIsbnIndex.setFrom("/Books"));
bookIsbnIndex.setType(IndexType.KEY);
return bookIsbnIndex;
}
或者,我们可以使用 XML 来创建 Index bean 定义,如下所示
<gfe:index id="BooksIsbnIndex" expression="isbn" from="/Books" type="KEY"/>
然而,现在您可以在应用程序域对象类型的字段上直接定义索引,您知道这些字段将用于查询谓词以加速这些查询。您甚至可以为应用程序存储库接口上用户定义的查询方法生成的 OQL 查询应用索引。
重新使用前面示例中的 Book 实体类,我们可以使用 @Indexed 注解标注 Book 中我们知道将在 BookRepository 接口中用查询方法定义的查询中使用的字段,如下所示
@Region("Books")
class Book {
@Id
private ISBN isbn;
@Indexed
private Author author;
private Category category;
private LocalDate releaseDate;
private Publisher publisher;
@LuceneIndexed
private String title;
}
在我们新的 Book 类定义中,我们用 @Indexed 注解了 author 字段,用 @LuceneIndexed 注解了 title 字段。此外,isbn 字段之前已用 Spring Data 的 @Id 注解标注,该注解标识包含 Book 实例唯一标识符的字段,并且在 Spring Data for Pivotal GemFire 中,@Id 注解的字段或属性在存储条目时用作区域中的键。
-
@Id注解的字段或属性会导致创建 Pivotal GemFireKEY索引。 -
@Indexed注解的字段或属性会导致创建 Pivotal GemFireHASH索引(默认)。 -
@LuceneIndexed注解的字段或属性会导致创建 Pivotal GemFire Lucene 索引,用于与 Pivotal GemFire 的 Lucene 集成和支持的基于文本的搜索。
当使用 @Indexed 注解而不设置任何属性时,索引的 name、expression 和 fromClause 将从添加了 @Indexed 注解的类的字段或属性派生。expression 就是字段或属性的名称。fromClause 从域对象类的 @Region 注解派生,如果未指定 @Region 注解,则从域对象类的简单名称派生。
当然,您可以显式设置任何 @Indexed 注解属性以覆盖 Spring Data for Pivotal GemFire 提供的默认值。
@Region("Books")
class Book {
@Id
private ISBN isbn;
@Indexed(name = "BookAuthorNameIndex", expression = "author.name", type = "FUNCTIONAL")
private Author author;
private Category category;
private LocalDate releaseDate;
private Publisher publisher;
@LuceneIndexed(name = "BookTitleIndex", destory = true)
private String title;
}
索引的 name(未显式设置时自动生成)也用作在 Spring 容器中注册的索引 bean 的名称。如有必要,此索引 bean 甚至可以通过名称注入到另一个应用程序组件中。
生成的索引名称遵循此模式:<Region Name><Field/Property Name><Index Type>Idx。例如,author 索引的名称将是 BooksAuthorHashIdx。
要启用索引,请使用 @EnableIndexing 注解应用程序类,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableEntityDefinedRegions
@EnableIndexing
class ServerApplication { .. }
除非同时声明 @EnableEntityDefinedRegions,否则 @EnablingIndexing 注解无效。本质上,索引是根据实体类类型上的字段或属性定义的,必须扫描实体类以检查实体的字段和属性是否存在索引注解。如果没有此扫描,将找不到索引注解。我们还强烈建议您限制扫描的范围。 |
虽然 Lucene 查询尚不支持 Pivotal GemFire 仓库的 Spring Data,但 SDG 通过使用熟悉的 Spring 模板设计模式提供了对 Pivotal GemFire Lucene 查询的全面支持。
最后,我们以一些使用索引时要记住的额外提示来结束本节
-
虽然执行 OQL 查询不需要 OQL 索引,但执行 Lucene 基于文本的搜索需要 Lucene 索引。
-
OQL 索引不会持久化到磁盘。它们只维护在内存中。因此,当 Pivotal GemFire 节点重新启动时,必须重建索引。
-
您还需要注意维护索引所带来的开销,特别是因为索引完全存储在内存中,尤其是在 Region 条目更新时。索引“维护”可以配置为异步任务。
当重新启动 Spring 应用程序时,您还可以使用另一种优化,即首先预定义所有索引,然后一次性创建它们。在 Spring Data for Pivotal GemFire 中,这在 Spring 容器刷新时发生。
您可以通过将 @EnableIndexing 注解上的 define 属性设置为 true 来预先定义索引并一次性创建它们。
有关更多详细信息,请参阅 Pivotal GemFire 用户指南中的“一次创建多个索引”。
创建合理的索引是一项重要任务,因为设计不当的索引弊大于利。
有关配置选项的完整列表,请参阅 @Indexed 注解和 @LuceneIndexed 注解 Javadoc。
有关 Pivotal GemFire OQL 查询的更多详细信息,请参阅此处。
有关 Pivotal GemFire 索引的更多详细信息,请参阅此处。
有关 Pivotal GemFire Lucene 查询的更多详细信息,请参阅此处。
6.13. 配置持续查询
Pivotal GemFire 的另一个非常重要且有用的功能是持续查询。
在万物互联的世界中,事件和数据流无处不在。能够实时处理大量数据流并对事件做出反应对于许多应用程序来说变得越来越重要。自动驾驶汽车就是一个例子。能够实时接收、过滤、转换、分析和处理数据是实时应用程序的关键区别和特征。
幸运的是,Pivotal GemFire 在这方面走在了时代的前面。通过使用持续查询 (CQ),客户端应用程序可以表达它感兴趣的数据或事件,并注册监听器以在事件发生时处理它们。客户端应用程序可能感兴趣的数据表示为 OQL 查询,其中查询谓词用于过滤或识别感兴趣的数据。当数据更改或添加并与已注册 CQ 的查询谓词中定义的条件匹配时,客户端应用程序会收到通知。
Spring Data for Pivotal GemFire 使得定义和注册 CQ 以及关联的监听器来处理 CQ 事件变得容易,而无需 Pivotal GemFire 繁琐的底层代码。SDG 基于注解的 CQ 新配置建立在持续查询监听器容器中现有持续查询支持的基础上。
例如,假设一个图书出版商希望注册兴趣并在任何时候 Book 的订单(需求)超过当前库存(供应)时收到通知。那么出版商的打印应用程序可能会注册以下 CQ
ClientCache 应用程序。@SpringBootApplication
@ClientCacheApplication(subcriptionEnabled = true)
@EnableContinuousQueries
class PublisherPrintApplication {
@ContinuousQuery(name = "DemandExceedsSupply", query =
"SELECT book.* FROM /Books book, /Inventory inventory
WHERE book.title = 'How to crush it in the Book business like Amazon"
AND inventory.isbn = book.isbn
AND inventory.available < (
SELECT sum(order.lineItems.quantity)
FROM /Orders order
WHERE order.status = 'pending'
AND order.lineItems.isbn = book.isbn
)
")
void handleSupplyProblem(CqEvent event) {
// start printing more books, fast!
}
}
要启用持续查询,请使用 @EnableContinuousQueries 注解您的应用程序类。
定义持续查询包括使用 @ContinuousQuery 注解任何 Spring @Component 注解的 POJO 类方法(与 SDG 的 Function 注解的 POJO 方法类似)。使用 @ContinuousQuery 注解定义的带有 CQ 的 POJO 方法会在任何时候添加或更改与查询谓词匹配的数据时被调用。
此外,POJO 方法签名应遵守ContinuousQueryListener 和 ContinuousQueryListenerAdapter 部分中概述的要求。
有关可用属性和配置设置的更多详细信息,请参阅 @EnableContinuousQueries 和 @ContinuousQuery 注解 Javadoc。
有关 Spring Data for Pivotal GemFire 持续查询支持的更多详细信息,请参阅此处。
有关 Pivotal GemFire 持续查询的更多详细信息,请参阅此处。
6.14. 配置 Spring 的缓存抽象
通过 Spring Data for Pivotal GemFire,Pivotal GemFire 可以用作 Spring 缓存抽象中的缓存提供程序。
在 Spring 的缓存抽象中,缓存注解(例如 @Cacheable)标识在调用潜在的昂贵操作之前执行缓存查找的缓存。应用程序服务方法的结果在操作调用后被缓存。
在 Spring Data for Pivotal GemFire 中,Spring Cache 直接对应于 Pivotal GemFire Region。在调用任何缓存注解的应用程序服务方法之前,Region 必须存在。这适用于任何标识服务操作中要使用的缓存的 Spring 缓存注解(即 @Cacheable、@CachePut 和 @CacheEvict)。
例如,我们的出版商的销售点 (PoS) 应用程序可能有一个功能可以在销售交易期间确定或查找 Book 的 Price,如下例所示
@Service
class PointOfSaleService
@Cacheable("BookPrices")
Price runPriceCheckFor(Book book) {
...
}
@Transactional
Receipt checkout(Order order) {
...
}
...
}
为了让您在使用 Spring Data for Pivotal GemFire 和 Spring 的缓存抽象时工作更轻松,基于注解的配置模型中添加了两个新功能。
考虑以下 Spring 缓存配置
@EnableCaching
class CachingConfiguration {
@Bean
GemfireCacheManager cacheManager(GemFireCache gemfireCache) {
GemfireCacheManager cacheManager = new GemfireCacheManager();
cacheManager.setCache(gemfireCache);
return cacheManager;
}
@Bean("BookPricesCache")
ReplicatedRegionFactoryBean<Book, Price> bookPricesRegion(GemFireCache gemfireCache) {
ReplicatedRegionFactoryBean<Book, Price> bookPricesRegion =
new ReplicatedRegionFactoryBean<>();
bookPricesRegion.setCache(gemfireCache);
bookPricesRegion.setClose(false);
bookPricesRegion.setPersistent(false);
return bookPricesRegion;
}
@Bean("PointOfSaleService")
PointOfSaleService pointOfSaleService(..) {
return new PointOfSaleService(..);
}
}
使用 Spring Data for Pivotal GemFire 的新功能,您可以将相同的缓存配置简化为以下内容
@EnableGemfireCaching
@EnableCachingDefinedRegions
class CachingConfiguration {
@Bean("PointOfSaleService")
PointOfSaleService pointOfSaleService(..) {
return new PointOfSaleService(..);
}
}
首先,@EnableGemfireCaching 注解取代了 Spring @EnableCaching 注解以及在 Spring 配置中声明显式 CacheManager bean 定义(名为“cacheManager”)的需要。
其次,@EnableCachingDefinedRegions 注解,就像“配置 Region”中描述的 @EnableEntityDefinedRegions 注解一样,检查整个 Spring 应用程序,缓存注解的服务组件以识别应用程序在运行时所需的所有缓存,并在应用程序启动时为这些缓存在 Pivotal GemFire 中创建 Region。
创建的 Region 仅限于创建 Region 的应用程序进程。如果应用程序是对等 Cache,则 Region 仅存在于应用程序节点上。如果应用程序是 ClientCache,则 SDG 会创建客户端 PROXY Region,并期望集群中服务器上已经存在同名 Region。
SDG 无法使用 Spring CacheResolver 在运行时解析操作中使用的缓存来确定服务方法所需的缓存。 |
| SDG 还支持应用程序服务组件上的 JCache (JSR-107) 缓存注解。有关可用于替代 JCache 缓存注解的等效 Spring 缓存注解,请参阅核心Spring Framework 参考指南。 |
有关将 Pivotal GemFire 用作 Spring 缓存抽象中的缓存提供程序的更多详细信息,请参阅“Spring 缓存抽象支持”部分。
有关 Spring 缓存抽象的更多详细信息,请参阅此处。
6.15. 配置集群配置推送
这可能是 Spring Data for Pivotal GemFire 中最令人兴奋的新功能。
当客户端应用程序类用 @EnableClusterConfiguration 注解时,客户端应用程序在 Spring 容器中定义和声明为 bean 的任何 Region 或索引都会“推送”到客户端连接到的服务器集群。不仅如此,这种“推送”以 Pivotal GemFire 在使用 HTTP 时会记住客户端推送的配置的方式执行。如果集群中的所有节点都宕机,它们会以与以前相同的配置重新启动。如果向集群添加新服务器,它将获得相同的配置。
从某种意义上说,这个功能与您手动使用 Gfsh 在集群中的所有服务器上创建 Region 和索引并没有太大区别。只是现在,借助 Spring Data for Pivotal GemFire,您不再需要使用 Gfsh 来创建 Region 和索引。您的 Spring Boot 应用程序,借助 Spring Data for Pivotal GemFire 的强大功能,已经包含创建 Region 和索引所需的所有配置元数据。
当您使用 Spring Data Repository 抽象时,我们知道您的应用程序将需要的所有 Region(例如由 @Region 注解的实体类定义的 Region)和索引(例如由 @Indexed 注解的实体字段和属性定义的索引)。
当您使用 Spring 的缓存抽象时,我们也知道您的应用程序的服务组件所需的所有缓存的所有 Region。
本质上,您只需通过使用 Spring Framework 及其所有 API 和功能(无论是通过注解元数据、Java、XML 还是其他方式表达,无论是用于配置、映射还是其他目的)开发应用程序,就已经告诉我们所需的一切。
重点是,您可以专注于应用程序的业务逻辑,同时使用框架的功能和支持基础设施(例如 Spring 的缓存抽象、Spring Data Repositories、Spring 的事务管理等),而 Spring Data for Pivotal GemFire 将为您处理这些框架功能所需的所有 Pivotal GemFire 底层代码。
将配置从客户端推送到集群中的服务器并让集群记住它,部分得益于 Pivotal GemFire 集群配置服务的使用。Pivotal GemFire 的集群配置服务也是 Gfsh 用于记录用户从 shell 发送到集群的与模式相关的更改(例如,gfsh> create region --name=Example --type=PARTITION)的相同服务。
当然,由于集群可能会“记住”客户端从上次运行推送的先前配置,因此 Spring Data for Pivotal GemFire 会小心不要覆盖服务器中已经定义的任何现有 Region 和索引。这尤其重要,例如,当 Region 已经包含数据时!
| 目前,没有选项可以覆盖任何现有的 Region 或索引定义。要重新创建 Region 或索引,您必须使用 Gfsh 首先销毁 Region 或索引,然后重新启动客户端应用程序,以便将配置再次推送到服务器。或者,您可以使用 Gfsh 手动(重新)定义 Region 和索引。 |
| 与 Gfsh 不同,Spring Data for Pivotal GemFire 仅支持从客户端在服务器上创建 Region 和索引。对于高级配置和用例,您应该使用 Gfsh 来管理(服务器端)集群。 |
要使用此功能,您必须在 Spring、Pivotal GemFire ClientCache 应用程序的类路径中显式声明 org.springframework:spring-web 依赖项。 |
考虑以下配置中表达的强大功能
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableCachingDefinedRegions
@EnableEntityDefinedRegions
@EnableIndexing
@EnableGemfireCaching
@EnableGemfireRepositories
@EnableClusterConfiguration
class ClientApplication { .. }
您立即获得一个 Spring Boot 应用程序,其中包含 Pivotal GemFire ClientCache 实例、Spring Data Repositories、Spring 缓存抽象以及 Pivotal GemFire 作为缓存提供程序(其中 Region 和索引不仅在客户端创建,而且推送到集群中的服务器)。
从那里,您只需要执行以下操作
-
定义带有映射和索引注解的应用程序域模型对象。
-
定义 Repository 接口以支持每个实体类型的数据访问基本操作和简单查询。
-
定义包含实体业务逻辑的服务组件。
-
在需要缓存、事务行为等的服务方法上声明适当的注解。
在这种情况下,没有任何内容与应用程序后端服务(如 Pivotal GemFire)所需的基础设施和底层代码相关。数据库用户具有类似的功能。现在 Spring 和 Pivotal GemFire 开发人员也具备了。
当与以下 Spring Data for Pivotal GemFire 注解结合使用时,这个应用程序只需很少的努力就能真正起飞
-
@EnableContinuousQueries -
@EnableGemfireFunctionExecutions -
@EnableGemfireCacheTransactions
有关更多详细信息,请参阅@EnableClusterConfiguration 注解 Javadoc。
6.16. 配置 SSL
与通过网络传输数据序列化同样重要的是在传输过程中保护数据。当然,在 Java 中实现这一点的方法是使用安全套接字扩展 (SSE) 和传输层安全 (TLS)。
要启用 SSL,请使用 @EnableSsl 注解您的应用程序类,如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableSsl
public class ClientApplication { .. }
然后,您需要设置必要的 SSL 配置属性或特性:密钥库、用户名/密码等。
您可以单独配置不同的 Pivotal GemFire 组件(GATEWAY、HTTP、JMX、LOCATOR 和 SERVER)使用 SSL,或者可以使用 CLUSTER 枚举值集体配置它们使用 SSL。
您可以使用嵌套的 @EnableSsl 注解、components 属性以及 Component 枚举中的枚举值来指定 SSL 配置设置应应用于哪些 Pivotal GemFire 组件,如下所示
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableSsl(components = { GATEWAY, LOCATOR, SERVER })
public class ClientApplication { .. }
此外,您还可以使用相应的注解属性或相关的配置属性来指定组件级别的 SSL 配置(ciphers、protocols 和 keystore/truststore 信息)。
有关更多详细信息,请参阅@EnableSsl 注解 Javadoc。
有关 Pivotal GemFire SSL 支持的更多详细信息,请参阅此处。
6.17. 配置安全性
毫无疑问,应用程序安全至关重要,Spring Data for Pivotal GemFire 为保护 Pivotal GemFire 客户端和服务器提供了全面的支持。
最近,Pivotal GemFire 推出了一个新的集成安全框架(取代了其旧的身份验证和授权安全模型),用于处理身份验证和授权。这个新安全框架的主要特点和优点之一是它与 Apache Shiro 集成,因此可以将身份验证和授权请求委托给 Apache Shiro 以强制执行安全性。
本节的其余部分演示了 Spring Data for Pivotal GemFire 如何进一步简化 Pivotal GemFire 的安全故事。
6.17.1. 配置服务器安全性
您可以通过几种不同的方式为 Pivotal GemFire 集群中的服务器配置安全性。
-
实现 Pivotal GemFire
org.apache.geode.security.SecurityManager接口,并设置 Pivotal GemFire 的security-manager属性,以使用完全限定类名引用您的应用程序SecurityManager实现。或者,用户可以在创建 Pivotal GemFire 对等Cache时构建并初始化其SecurityManager实现的实例,并使用 CacheFactory.setSecurityManager(:SecurityManager) 方法进行设置。 -
创建包含为您的应用程序定义的用户名、角色和权限的 Apache Shiro
shiro.ini文件,然后设置 Pivotal GemFiresecurity-shiro-init属性以引用此shiro.ini文件,该文件必须在CLASSPATH中可用。 -
仅使用 Apache Shiro,使用 Spring Data for Pivotal GemFire 的新
@EnableSecurity注解来注解您的 Spring Boot 应用程序类,并在 Spring 容器中将一个或多个 Apache ShiroRealm定义为 bean,以访问您的应用程序的安全元数据(即授权用户、角色和权限)。
第一种方法的问题是您必须实现自己的 SecurityManager,这可能非常繁琐且容易出错。实现自定义 SecurityManager 在从存储元数据的任何数据源(例如 LDAP 甚至专有的内部数据源)访问安全元数据方面提供了一些灵活性。但是,这个问题已经通过配置和使用 Apache Shiro Realm 解决了,后者更广为人知且不特定于 Pivotal GemFire。
第二种方法,使用 Apache Shiro INI 文件,稍微好一些,但您仍然需要首先熟悉 INI 文件格式。此外,INI 文件是静态的,在运行时不容易更新。
第三种方法是最理想的,因为它遵循广为人知和行业接受的概念(即 Apache Shiro 的安全框架),并且易于设置,如下例所示
@SpringBootApplication
@CacheServerApplication
@EnableSecurity
class ServerApplication {
@Bean
PropertiesRealm shiroRealm() {
PropertiesRealm propertiesRealm = new PropertiesRealm();
propertiesRealm.setResourcePath("classpath:shiro.properties");
propertiesRealm.setPermissionResolver(new GemFirePermissionResolver());
return propertiesRealm;
}
}
上述示例中配置的 Realm 可以很容易地是 Apache Shiro 支持的任何 Realm |
-
支持 INI 格式的
Realm。
您甚至可以创建 Apache Shiro Realm 的自定义实现。
有关更多详细信息,请参阅 Apache Shiro 的Realm 文档。
当 Apache Shiro 在集群中服务器的 CLASSPATH 上,并且在 Spring 容器中定义了一个或多个 Apache Shiro Realm 作为 bean 时,Spring Data for Pivotal GemFire 会检测此配置并在使用 @EnableSecurity 注解时使用 Apache Shiro 作为安全提供程序来保护您的 Pivotal GemFire 服务器。
| 有关 Spring Data for Pivotal GemFire 支持使用 Apache Shiro 的 Pivotal GemFire 新集成安全框架的更多信息,请参阅此spring.io 博客文章。 |
有关可用属性和相关配置属性的更多详细信息,请参阅 @EnableSecurity 注解 Javadoc。
有关 Pivotal GemFire 安全性的更多详细信息,请参阅此处。
6.17.2. 配置客户端安全性
如果不讨论如何保护基于 Spring 的 Pivotal GemFire 缓存客户端应用程序,安全故事就不完整。
Pivotal GemFire 保护客户端应用程序的过程,老实说,相当复杂。简而言之,您需要
-
提供
org.apache.geode.security.AuthInitialize接口的实现。 -
设置 Pivotal GemFire
security-client-auth-init(系统)属性以引用自定义的、应用程序提供的AuthInitialize接口。 -
在专有的 Pivotal GemFire
gfsecurity.properties文件中指定用户凭据。
Spring Data for Pivotal GemFire 通过使用与服务器应用程序中相同的 @EnableSecurity 注解简化了所有这些步骤。换句话说,相同的 @EnableSecurity 注解处理客户端和服务器应用程序的安全性。此功能使得用户在决定将应用程序从嵌入式对等 Cache 应用程序切换到 ClientCache 应用程序时更容易。只需将 SDG 注解从 @PeerCacheApplication 或 @CacheServerApplication 更改为 @ClientCacheApplication,即可完成。
实际上,您只需在客户端执行以下操作
@EnableSecurity 的 Spring 客户端应用程序@SpringBootApplication
@ClientCacheApplication
@EnableSecurity
class ClientApplication { .. }
然后,您可以定义包含所需用户名和密码的熟悉的 Spring Boot application.properties 文件,如下例所示,即可完成
application.properties 文件spring.data.gemfire.security.username=jackBlack
spring.data.gemfire.security.password=b@cK!nB1@cK
默认情况下,当 application.properties 文件位于应用程序 CLASSPATH 的根目录时,Spring Boot 可以找到它。当然,Spring 支持使用其资源抽象来定位资源的多种方式。 |
有关可用属性和相关配置属性的更多详细信息,请参阅 @EnableSecurity 注解 Javadoc。
有关 Pivotal GemFire 安全性的更多详细信息,请参阅此处。
6.18. 配置技巧
以下提示可以帮助您充分利用新的基于注解的配置模型
6.18.1. 配置组织
正如我们在“配置集群配置推送”一节中所看到的,当使用注解启用许多 Pivotal GemFire 或 Spring Data for Pivotal GemFire 功能时,我们开始在 Spring @Configuration 或 @SpringBootApplication 类上堆叠大量注解。在这种情况下,开始对配置进行一些模块化是很有意义的。
例如,考虑以下声明
ClientCache 应用程序@SpringBootApplication
@ClientCacheApplication
@EnableContinuousQueries
@EnableCachingDefinedRegions
@EnableEntityDefinedRegions
@EnableIndexing
@EnableGemfireCacheTransactions
@EnableGemfireCaching
@EnableGemfireFunctionExecutions
@EnableGemfireRepositories
@EnableClusterConfiguration
class ClientApplication { .. }
我们可以按关注点将此配置分解,如下所示
ClientCache 应用程序(启动)@SpringBootApplication
@Import({ GemFireConfiguration.class, CachingConfiguration.class,
FunctionsConfiguration.class, QueriesConfiguration.class,
RepositoriesConfiguration.class })
class ClientApplication { .. }
@ClientCacheApplication
@EnableClusterConfiguration
@EnableGemfireCacheTransactions
class GemFireConfiguration { .. }
@EnableGemfireCaching
@EnableCachingDefinedRegions
class CachingConfiguration { .. }
@EnableGemfireFunctionExecutions
class FunctionsConfiguration { .. }
@EnableContinuousQueries
class QueriesConfiguration {
@ContinuousQuery(..)
void processCqEvent(CqEvent event) {
...
}
}
@EnableEntityDefinedRegions
@EnableGemfireRepositories
@EnableIndexing
class RepositoriesConfiguration { .. }
虽然对 Spring 框架无关紧要,但我们通常建议以可读性为目标,以方便下一个需要维护代码的人(这可能在未来的某个时候是您)。
6.18.2. 附加基于配置的注解
以下 SDG 注解未在此参考文档中讨论,原因要么是该注解支持 Pivotal GemFire 的已弃用功能,要么是有更好、替代的方法可以实现该注解提供的功能
-
@EnableAuth:启用 Pivotal GemFire 的旧身份验证和授权安全模型。(已弃用。如“配置安全性”中所述,可以使用 SDG 的@EnableSecurity注解在客户端和服务器上启用 Pivotal GemFire 的新集成安全框架。) -
@EnableAutoRegionLookup:不推荐。本质上,此注解支持查找外部配置元数据(例如cache.xml或应用于服务器的集群配置)中定义的 Region,并自动将这些 Region 注册为 Spring 容器中的 bean。此注解对应于 SDG XML 命名空间中的<gfe:auto-region-lookup>元素。更多详细信息可参阅此处。用户在使用 Spring 和 Spring Data for Pivotal GemFire 时通常应首选 Spring 配置。请参阅“配置 Region”和“配置集群配置推送”作为替代。 -
@EnableBeanFactoryLocator:启用 SDGGemfireBeanFactoryLocator功能,该功能仅在使用外部配置元数据(例如cache.xml)时有用。例如,如果您在cache.xml中定义的 Region 上定义了CacheLoader,您仍然可以使用 Spring 配置中定义的(例如)关系数据库DataSourcebean 来自动装配此CacheLoader。此注解利用了 SDG 的此功能,如果您有大量旧版配置元数据(例如cache.xml文件),可能会很有用。 -
@EnableGemFireAsLastResource:在与 Pivotal GemFire 的全局 - JTA 事务管理中讨论。 -
@EnableMcast:启用 Pivotal GemFire 的旧对等发现机制,该机制使用基于 UDP 的多播网络。(已弃用。请改用 Pivotal GemFire Locator。请参阅“配置嵌入式 Locator”)。 -
@EnableRegionDataAccessTracing:用于调试。此注解通过注册一个 AOP 切面来启用对 Region 上执行的所有数据访问操作的跟踪,该切面代理 Spring 容器中声明为 bean 的所有 Region,拦截 Region 操作并记录事件。
6.19. 结论
正如我们在前几节中学到的,Spring Data for Pivotal GemFire 的新基于注解的配置模型提供了巨大的力量。希望它能实现其目标,让您在使用 Pivotal GemFire 和 Spring 时更轻松地快速和轻松入门。
请记住,当您使用新注解时,您仍然可以使用 Java 配置或 XML 配置。您甚至可以通过在 Spring @Configuration 或 @SpringBootApplication 类上使用 Spring 的 @Import 和 @ImportResource 注解来组合所有三种方法。当您明确提供一个否则将由 Spring Data for Pivotal GemFire 使用其中一个注解提供的 bean 定义时,基于注解的配置就会退避。
|
在某些情况下,您甚至可能需要回退到 Java 配置,就像在 例如,您需要 Java 或 XML 配置的另一个情况是配置 Pivotal GemFire WAN 组件,目前这些组件没有任何注解配置支持。但是,定义和注册 WAN 组件只需要在 Spring |
这些注解并非旨在处理所有情况。这些注解旨在帮助您尽快和轻松地启动并运行,尤其是在开发期间。
我们希望您会喜欢这些新功能!
6.20. 基于注解的配置快速入门
以下部分概述了 SDG 注解,以便快速入门。
| 所有注解都提供额外的配置属性以及相关的属性,以便在运行时方便地自定义 Pivotal GemFire 的配置和行为。但是,通常情况下,不需要任何属性或相关属性即可使用特定的 Pivotal GemFire 功能。只需声明注解即可启用该功能,即可完成。有关更多详细信息,请参阅每个注解的单独 Javadoc。 |
6.20.1. 配置 ClientCache 应用程序
要配置和引导 Pivotal GemFire ClientCache 应用程序,请使用以下内容
@SpringBootApplication
@ClientCacheApplication
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
有关更多详细信息,请参阅使用 Spring 配置 Pivotal GemFire 应用程序。
6.20.2. 配置对等 Cache 应用程序
要配置和引导 Pivotal GemFire 对等 Cache 应用程序,请使用以下内容
@SpringBootApplication
@PeerCacheApplication
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
如果您想启用一个允许 ClientCache 应用程序连接到此服务器的 CacheServer,那么只需将 @PeerCacheApplication 注解替换为 @CacheServerApplication 注解即可。这将启动一个在“localhost”上运行的 CacheServer,监听默认的 CacheServer 端口 40404。 |
有关更多详细信息,请参阅使用 Spring 配置 Pivotal GemFire 应用程序。
6.20.3. 配置嵌入式 Locator
使用 @EnableLocator 注解您的 Spring @PeerCacheApplication 或 @CacheServerApplication 类,以启动一个绑定到所有 NIC 并监听默认 Locator 端口 10334 的嵌入式 Locator,如下所示
@SpringBootApplication
@CacheServerApplication
@EnableLocator
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@EnableLocator 只能与 Pivotal GemFire 服务器应用程序一起使用。 |
有关更多详细信息,请参阅配置嵌入式 Locator。
6.20.4. 配置嵌入式 Manager
使用 @EnableManager 注解您的 Spring @PeerCacheApplication 或 @CacheServerApplication 类,以启动一个绑定到所有 NIC 并监听默认 Manager 端口 1099 的嵌入式 Manager,如下所示
@SpringBootApplication
@CacheServerApplication
@EnableManager
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@EnableManager 只能与 Pivotal GemFire 服务器应用程序一起使用。 |
有关更多详细信息,请参阅配置嵌入式 Manager。
6.20.5. 配置嵌入式 HTTP 服务器
使用 @EnableHttpService 注解您的 Spring @PeerCacheApplication 或 @CacheServerApplication 类,以启动监听端口 7070 的嵌入式 HTTP 服务器 (Jetty),如下所示
@SpringBootApplication
@CacheServerApplication
@EnableHttpService
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@EnableHttpService 只能与 Pivotal GemFire 服务器应用程序一起使用。 |
有关更多详细信息,请参阅配置嵌入式 HTTP 服务器。
6.20.6. 配置嵌入式 Memcached 服务器
使用 @EnableMemcachedServer 注解您的 Spring @PeerCacheApplication 或 @CacheServerApplication 类,以启动监听端口 11211 的嵌入式 Memcached 服务器 (Gemcached),如下所示
@SpringBootApplication
@CacheServerApplication
@EnableMemcachedServer
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@EnableMemcachedServer 只能与 Pivotal GemFire 服务器应用程序一起使用。 |
有关更多详细信息,请参阅配置嵌入式 Memcached 服务器 (Gemcached)。
6.20.7. 配置嵌入式 Redis 服务器
使用 @EnableRedisServer 注解您的 Spring @PeerCacheApplication 或 @CacheServerApplication 类,以启动监听端口 6379 的嵌入式 Redis 服务器,如下所示
@SpringBootApplication
@CacheServerApplication
@EnableRedisServer
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
@EnableRedisServer 只能与 Pivotal GemFire 服务器应用程序一起使用。 |
您必须在 Spring [Boot] 应用程序的类路径上显式声明 org.apache.geode:geode-redis 模块。 |
有关更多详细信息,请参阅配置嵌入式 Redis 服务器。
6.20.8. 配置日志记录
要配置或调整 Pivotal GemFire 日志记录,请使用 @EnableLogging 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableLogging(logLevel="trace")
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
默认 log-level 是“config”。此外,此注解不会调整应用程序中的日志级别,只会调整 Pivotal GemFire 的日志级别。 |
有关更多详细信息,请参阅配置日志记录。
6.20.9. 配置统计信息
要在运行时收集 Pivotal GemFire 统计信息,请使用 @EnableStatistics 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableStatistics
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
有关更多详细信息,请参阅配置统计信息。
6.20.10. 配置 PDX
要启用 Pivotal GemFire PDX 序列化,请使用 @EnablePdx 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnablePdx
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
Pivotal GemFire PDX 序列化是 Java 序列化的替代方案,具有许多附加优势。例如,它能轻松使您的所有应用程序域模型类型可序列化,而无需实现 java.io.Serializable。 |
默认情况下,SDG 配置 MappingPdxSerializer 来序列化您的应用程序域模型类型,它无需任何特殊配置即可正确识别需要序列化的应用程序域对象,然后执行序列化,因为 MappingPdxSerializer 中的逻辑基于 Spring Data 的映射基础设施。有关更多详细信息,请参阅MappingPdxSerializer。 |
请参阅 @EnablePdx Javadoc。
有关更多详细信息,请参阅配置 PDX。
6.20.11. 配置 SSL
要启用 Pivotal GemFire SSL,请使用 @EnableSsl 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableSsl(components = SERVER)
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
最低限度,Pivotal GemFire 要求您使用适当的配置属性或特性指定密钥库和信任库。密钥库和信任库配置属性或特性可以引用同一个 KeyStore 文件。此外,如果 KeyStore 文件已加密,您需要指定用户名和密码才能访问该文件。 |
| Pivotal GemFire SSL 允许您配置系统中需要 TLS 的特定组件,例如客户端/服务器、Locator、Gateway 等。您还可以选择使用“ALL”来指定 Pivotal GemFire 的所有组件都使用 SSL。 |
请参阅 @EnableSsl Javadoc。
有关更多详细信息,请参阅配置 SSL。
6.20.12. 配置安全性
要启用 Pivotal GemFire 安全性,请使用 @EnableSecurity 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableSecurity
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
在服务器端,您必须配置对身份验证凭据的访问。您可以实现 Pivotal GemFire SecurityManager 接口或声明 1 个或多个 Apache Shiro Realms。有关更多详细信息,请参阅配置服务器安全性。 |
| 在客户端,您必须配置用户名和密码。有关更多详细信息,请参阅配置客户端安全性。 |
有关更多详细信息,请参阅配置安全性。
6.20.13. 配置 Pivotal GemFire 属性
要配置未被面向功能的 SDG 配置注解涵盖的其他低级 Pivotal GemFire 属性,请使用 @GemFireProperties 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@PeerCacheApplication
@EnableGemFireProperties(
cacheXmlFile = "/path/to/cache.xml",
conserveSockets = true,
groups = "GroupOne",
remoteLocators = "lunchbox[11235],mailbox[10101],skullbox[12480]"
)
public class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
}
| 一些 Pivotal GemFire 属性仅适用于客户端,而另一些仅适用于服务器。请查阅 Pivotal GemFire 文档以了解每个属性的正确用法。 |
有关更多详细信息,请参阅配置 Pivotal GemFire 属性。
6.20.14. 配置缓存
要使用 Pivotal GemFire 作为 Spring 缓存抽象中的缓存提供程序,并让 SDG 自动为您的应用程序服务组件所需的缓存创建 Pivotal GemFire Region,请使用 @EnableGemfireCaching 和 @EnableCachingDefinedRegions 注解您的 Spring, Pivotal GemFire 客户端或服务器应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableCachingDefinedRegions
@EnableGemfireCaching
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
然后,只需继续定义需要缓存的应用程序服务,如下所示
@Service
public class BookService {
@Cacheable("Books")
public Book findBy(ISBN isbn) {
...
}
}
@EnableCachingDefinedRegions 是可选的。也就是说,您可以根据需要手动定义 Region。 |
有关更多详细信息,请参阅配置 Spring 的缓存抽象。
6.20.15. 配置持久化应用程序的 Region、索引、Repository 和实体
为了轻松创建 Spring, Pivotal GemFire 持久化客户端或服务器应用程序,请使用 @EnableEntityDefinedRegions、@EnableGemfireRepositories 和 @EnableIndexing 注解您的应用程序类,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableEntityDefinedRegions(basePackageClasses = Book.class)
@EnableGemfireRepositories(basePackageClasses = BookRepository.class)
@EnableIndexing
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
使用 @EnableIndexing 注解时,需要 @EnableEntityDefinedRegions 注解。有关更多详细信息,请参阅配置索引。 |
接下来,定义您的实体类并使用 @Region 映射注解来指定存储您的实体的 Region。使用 @Indexed 注解来定义应用程序查询中使用的实体字段上的索引,如下所示
package example.app.model;
import ...;
@Region("Books")
public class Book {
@Id
private ISBN isbn;
@Indexed;
private Author author;
@Indexed
private LocalDate published;
@LuceneIndexed
private String title;
}
@Region("Books") 实体类注解由 @EnableEntityDefinedRegions 使用,以确定应用程序所需的 Region。有关更多详细信息,请参阅配置特定类型 Region 和POJO 映射。 |
最后,使用简单的查询定义您的 CRUD Repository,以持久化和访问 Books,如下所示
package example.app.repo;
import ...;
public interface BookRepository extends CrudRepository {
List<Book> findByAuthorOrderByPublishedDesc(Author author);
}
| 有关更多详细信息,请参阅Spring Data for Pivotal GemFire Repository。 |
请参阅 @Region Javadoc。
请参阅 @Indexed Javadoc。
有关更多详细信息,请参阅配置 Region。
有关更多详细信息,请参阅Spring Data for Pivotal GemFire Repository。
6.20.16. 从集群定义的 Region 配置客户端 Region
或者,您可以使用 @EnableClusterDefinedRegions 从集群中已定义的 Region 定义客户端 [*PROXY] Region,如下所示
@SpringBootApplication
@ClientCacheApplication
@EnableClusterDefinedRegions
@EnableGemfireRepositories
public class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
...
}
有关更多详细信息,请参阅配置集群定义的 Region。
6.20.17. 配置函数
Pivotal GemFire 函数在分布式计算场景中非常有用,在这种场景中,需要数据的潜在昂贵计算可以在集群中的节点上并行执行。在这种情况下,将逻辑带到数据所在(存储)的位置比请求和获取数据以供计算处理更有效。
将 @EnableGemfireFunctions 与 @GemfireFunction 注解一起使用,以启用作为 POJO 方法实现的 Pivotal GemFire 函数定义,如下所示
@PeerCacheApplication
@EnableGemfireFunctions
class ServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServerApplication.class, args);
}
@GemfireFunction
Integer computeLoyaltyPoints(Customer customer) {
...
}
}
将 @EnableGemfireFunctionExecutions 与其中一个函数调用注解一起使用:@OnMember、@OnMembers、@OnRegion、@OnServer 和 @OnServers。
@ClientCacheApplication
@EnableGemfireFunctionExecutions(basePackageClasses = CustomerRewardsFunction.class)
class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
@OnRegion("Customers")
interface CustomerRewardsFunctions {
Integer computeLoyaltyPoints(Customer customer);
}
有关更多详细信息,请参阅函数执行的注解支持。
6.20.18. 配置持续查询
实时事件流处理对于数据密集型应用程序来说变得越来越重要,主要是为了及时响应用户请求。Pivotal GemFire 持续查询 (CQ) 将帮助您非常轻松地完成这项相当复杂的任务。
通过使用 @EnableContinuousQueries 注解您的应用程序类来启用 CQ,并定义您的 CQ 以及相关的事件处理程序,如下所示
@ClientCacheApplication
@EnableContinuousQueries
class ClientApplication {
public static void main(String[] args) {
SpringApplication.run(ClientApplication.class, args);
}
}
然后,通过使用 @ContinousQuery 注解相关的处理方法来定义您的 CQ,如下所示
@Service
class CustomerService {
@ContinuousQuery(name = "CustomerQuery", query = "SELECT * FROM /Customers c WHERE ...")
public void process(CqEvent event) {
...
}
}
每当发生事件更改 Customer 数据以匹配持续 OQL 查询 (CQ) 中的谓词时,都会调用 process 方法。
| Pivotal GemFire CQ 仅是客户端功能。 |
6.20.19. 配置集群配置
当使用 Pivotal GemFire 作为 Pivotal GemFire ClientCache 应用程序开发 Spring Data 应用程序时,在开发过程中将服务器配置与客户端在客户端/服务器拓扑中匹配非常有用。事实上,Pivotal GemFire 期望当您在客户端上有一个 "/Example" PROXY Region 时,服务器中存在一个同名(即 "Example")的匹配 Region。
您可以使用 Gfsh 创建应用程序所需的所有 Region 和索引,或者,您可以在运行 Spring Data 应用程序时简单地推送在开发过程中已经表达的配置元数据。
这就像用 @EnableClusterConfiguration(..) 注解您的主应用程序类一样简单
@EnableClusterConfiguration@ClientCacheApplication
@EnableClusterConfiguration(useHttp = true)
class ClientApplication {
...
}
| 大多数情况下,当使用客户端/服务器拓扑时,特别是在生产环境中,集群的服务器将使用 Gfsh 启动。在这种情况下,通常使用 HTTP(S) 将配置元数据(例如 Region 和索引定义)发送到集群。当使用 HTTP 时,配置元数据被发送到集群中的 Manager,并一致地分发到集群中的服务器节点。 |
为了使用 @EnableClusterConfiguration,您必须在 Spring 应用程序类路径中声明 org.springframework:spring-web 依赖项。 |
有关更多详细信息,请参阅配置集群配置推送。
6.20.20. 配置 GatewayReceivers
不同 Pivotal GemFire 集群之间的数据复制是一种日益重要的容错和高可用性 (HA) 机制。Pivotal GemFire WAN 复制是一种机制,允许一个 Pivotal GemFire 集群以可靠且容错的方式将其数据复制到另一个 Pivotal GemFire 集群。
Pivotal GemFire WAN 复制需要配置两个组件
-
GatewayReceiver- 接收来自远程 Pivotal GemFire 集群的GatewaySender的数据的 WAN 复制组件。 -
GatewaySender- 将数据发送到远程 Pivotal GemFire 集群的GatewayReceiver的 WAN 复制组件。
要启用 GatewayReceiver,应用程序类需要使用 @EnableGatewayReceiver 注解,如下所示
@CacheServerApplication
@EnableGatewayReceiver(manualStart = false, startPort = 10000, endPort = 11000, maximumTimeBetweenPings = 1000,
socketBufferSize = 16384, bindAddress = "localhost",transportFilters = {"transportBean1", "transportBean2"},
hostnameForSenders = "hostnameLocalhost"){
...
...
}
}
class MySpringApplication { .. }
Pivotal GemFire GatewayReceiver 仅是服务器端功能,只能在 CacheServer 或对等 Cache 节点上配置。 |
6.20.21. 配置 GatewaySenders
要启用 GatewaySender,应用程序类需要使用 @EnableGatewaySenders 和 @EnableGatewaySender 注解,如下所示
@CacheServerApplication
@EnableGatewaySenders(gatewaySenders = {
@EnableGatewaySender(name = "GatewaySender", manualStart = true,
remoteDistributedSystemId = 2, diskSynchronous = true, batchConflationEnabled = true,
parallel = true, persistent = false,diskStoreReference = "someDiskStore",
orderPolicy = OrderPolicyType.PARTITION, alertThreshold = 1234, batchSize = 100,
eventFilters = "SomeEventFilter", batchTimeInterval = 2000, dispatcherThreads = 22,
maximumQueueMemory = 400,socketBufferSize = 16384,
socketReadTimeout = 4000, regions = { "Region1"}),
@EnableGatewaySender(name = "GatewaySender2", manualStart = true,
remoteDistributedSystemId = 2, diskSynchronous = true, batchConflationEnabled = true,
parallel = true, persistent = false, diskStoreReference = "someDiskStore",
orderPolicy = OrderPolicyType.PARTITION, alertThreshold = 1234, batchSize = 100,
eventFilters = "SomeEventFilter", batchTimeInterval = 2000, dispatcherThreads = 22,
maximumQueueMemory = 400, socketBufferSize = 16384,socketReadTimeout = 4000,
regions = { "Region2" })
}){
class MySpringApplication { .. }
}
Pivotal GemFire GatewaySender 仅是服务器端功能,只能在 CacheServer 或对等 Cache 节点上配置。 |
在上面的示例中,应用程序配置了两个 Region,Region1 和 Region2。此外,将配置两个 GatewaySenders 来服务这两个 Region。GatewaySender1 将配置为复制 Region1 的数据,GatewaySender2 将配置为复制 Region2 的数据。
如所示,每个 GatewaySender 属性都可以在每个 EnableGatewaySender 注解上配置。
也可以采用更通用的“默认”属性方法,其中所有属性都在 EnableGatewaySenders 注解上配置。这样,一组通用的默认值可以在父注解上设置,然后根据需要由子注解覆盖,如下所示
@CacheServerApplication
@EnableGatewaySenders(gatewaySenders = {
@EnableGatewaySender(name = "GatewaySender", transportFilters = "transportBean1", regions = "Region2"),
@EnableGatewaySender(name = "GatewaySender2")},
manualStart = true, remoteDistributedSystemId = 2,
diskSynchronous = false, batchConflationEnabled = true, parallel = true, persistent = true,
diskStoreReference = "someDiskStore", orderPolicy = OrderPolicyType.PARTITION, alertThreshold = 1234, batchSize = 1002,
eventFilters = "SomeEventFilter", batchTimeInterval = 2000, dispatcherThreads = 22, maximumQueueMemory = 400,
socketBufferSize = 16384, socketReadTimeout = 4000, regions = { "Region1", "Region2" },
transportFilters = { "transportBean2", "transportBean1" })
class MySpringApplication { .. }
当 regions 属性为空或未填充时,GatewaySender(s) 将自动附加到应用程序中配置的每个 Region。 |
7. 使用 Pivotal GemFire API
一旦配置了 Pivotal GemFire Cache 和 Region,就可以将它们注入到应用程序对象中并使用。本章描述了与 Spring 事务管理功能和 DAO 异常层次结构的集成。本章还涵盖了对 Pivotal GemFire 管理对象的依赖注入的支持。
7.1. GemfireTemplate
与 Spring 提供的许多其他高级抽象一样,Spring Data for Pivotal GemFire 提供了一个**模板**来简化 Pivotal GemFire 数据访问操作。该类提供了几个包含常见 Region 操作的方法,但还提供了通过使用 GemfireCallback **执行**针对原生 Pivotal GemFire API 的代码而无需处理 Pivotal GemFire 检查异常的能力。
模板类需要一个 Pivotal GemFire Region,并且一旦配置,它是线程安全的,并且可以在多个应用程序类中重用
<bean id="gemfireTemplate" class="org.springframework.data.gemfire.GemfireTemplate" p:region-ref="SomeRegion"/>
一旦模板配置完成,开发人员就可以将其与 GemfireCallback 一起使用,直接操作 Pivotal GemFire Region,而无需处理检查异常、线程或资源管理问题
template.execute(new GemfireCallback<Iterable<String>>() {
public Iterable<String> doInGemfire(Region region)
throws GemFireCheckedException, GemFireException {
Region<String, String> localRegion = (Region<String, String>) region;
localRegion.put("1", "one");
localRegion.put("3", "three");
return localRegion.query("length < 5");
}
});
为了充分利用 Pivotal GemFire 查询语言的强大功能,开发人员可以使用 find 和 findUnique 方法,与 query 方法相比,它们可以跨多个 Region 执行查询、执行投影等。
当查询选择多个项目(通过 SelectResults)时,应使用 find 方法;顾名思义,当只返回一个对象时,应使用 findUnique。
7.2. 异常转换
使用新的数据访问技术不仅需要适应新的 API,还需要处理该技术特有的异常。
为了适应异常处理情况,Spring Framework 提供了一个与技术无关且一致的异常层次结构,它将应用程序从专有且通常是“检查型”异常抽象为一组集中的运行时异常。
如《Spring Framework》文档中所述,异常转换可以通过使用 @Repository 注解和 AOP,通过定义 PersistenceExceptionTranslationPostProcessor bean 透明地应用于您的数据访问对象 (DAO)。只要声明了 CacheFactoryBean(例如,使用 <gfe:cache/> 或 <gfe:client-cache> 声明),就会启用相同的异常转换功能,因为它充当异常转换器并由 Spring 基础设施自动检测并相应地使用。
7.3. 本地缓存事务管理
Spring Framework 最受欢迎的功能之一是事务管理。
如果您不熟悉 Spring 的事务抽象,那么我们强烈建议您阅读有关 Spring 的事务管理基础设施,因为它提供了一个一致的编程模型,可以在多个 API 中透明地工作,并且可以编程或声明式地配置(最受欢迎的选择)。
对于 Pivotal GemFire,Spring Data for Pivotal GemFire 提供了一个专用的、每个缓存的 PlatformTransactionManager,一旦声明,它允许通过 Spring 以原子方式执行 Region 操作
<gfe:transaction-manager id="txManager" cache-ref="myCache"/>
如果 Pivotal GemFire 缓存是在默认名称 gemfireCache 下定义的,则可以通过消除 cache-ref 属性来进一步简化上述示例。与其他 Spring Data for Pivotal GemFire 命名空间元素一样,如果未配置缓存 bean 名称,则将使用上述命名约定。此外,如果未明确指定,事务管理器名称为“gemfireTransactionManager”。 |
目前,Pivotal GemFire 支持带有**读已提交**隔离的乐观事务。此外,为了保证这种隔离,开发人员应避免进行手动修改缓存中现有值的**原地**更改。为了防止这种情况发生,事务管理器默认将缓存配置为使用**读时复制**语义,这意味着每次执行读取时都会创建实际值的克隆。如果需要,可以通过 copyOnRead 属性禁用此行为。
由于启用**读时复制**时会复制给定键的值,因此您必须随后调用 Region.put(key, value) 才能以事务方式更新值。
有关底层 Geode 事务管理器的语义和行为的更多信息,请参阅 Geode CacheTransactionManager Javadoc 以及文档。
7.4. 全局 JTA 事务管理
Pivotal GemFire 也可以参与全局的、基于 JTA 的事务,例如由 Java EE 应用程序服务器(例如 WebSphere 应用程序服务器 (WAS))使用容器管理事务 (CMT) 以及其他 JTA 资源管理的事务。
然而,与许多其他 JTA“兼容”资源(例如 ActiveMQ 等 JMS 消息代理)不同,Pivotal GemFire **不是** XA 兼容资源。因此,Pivotal GemFire 必须在 JTA 事务中(准备阶段)定位为“最后一个资源”,因为它不实现两阶段提交协议,或者更确切地说不处理分布式事务。
许多能够进行 CMT 的受管环境都支持 JTA 事务中的“Last Resource”、非 XA 兼容资源,尽管 JTA 规范中并未实际要求。有关非 XA 兼容“Last Resource”含义的更多信息,请参阅 Red Hat 的文档。事实上,Red Hat 的 JBoss 项目 Narayana 就是这样一个 LGPL 开源实现。Narayana 将此称为“Last Resource Commit Optimization”(LRCO)。更多详细信息可参阅此处。
然而,无论您是在具有支持“Last Resource”的开源 JTA 事务管理实现的独立环境中使用 Pivotal GemFire,还是在托管环境(例如 WAS 等 Java EE AS)中使用,Spring Data for Pivotal GemFire 都能满足您的需求。
您必须完成一系列步骤才能正确地将 Pivotal GemFire 用作涉及多个事务资源的 JTA 事务中的“Last Resource”。此外,在这种安排中只能有一个非 XA 兼容资源(例如 Pivotal GemFire)。
1) 首先,您必须完成 Pivotal GemFire 文档此处的步骤 1-4。
| 上述 #1 独立于您的 Spring [Boot] 和/或 [Data for Pivotal GemFire] 应用程序,并且必须成功完成。 |
2) 参考 Pivotal GemFire 文档中的步骤 5,当您使用 @EnableGemFireAsLastResource 注解时,Spring Data for Pivotal GemFire 的注解支持将尝试为您设置 GemFireCache 的 copyOnRead 属性。
但是,如果 SDG 的自动配置在此方面不成功,则必须在 <gfe:cache> 或 <gfe:client-cache> XML 元素中明确设置 copy-on-read 属性,或者在 JavaConfig 中将 CacheFactoryBean 类的 copyOnRead 属性设置为 **true**。例如
ClientCache XML
<gfe:client-cache ... copy-on-read="true"/>
ClientCache JavaConfig
@Bean
ClientCacheFactoryBean gemfireCache() {
ClientCacheFactoryBean gemfireCache = new ClientCacheFactoryBean();
gemfireCache.setCopyOnRead(true);
return gemfireCache;
}
对等 Cache XML
<gfe:cache ... copy-on-read="true"/>
对等 Cache JavaConfig
@Bean
CacheFactoryBean gemfireCache() {
CacheFactoryBean gemfireCache = new CacheFactoryBean();
gemfireCache.setCopyOnRead(true);
return gemfireCache;
}
明确设置 copy-on-read 属性或 copyOnRead 属性实际上没有必要。启用事务管理会处理读时复制。 |
3) 此时,您**跳过** Pivotal GemFire 文档中的步骤 6-8,让 *Spring Data Geode* 发挥其魔力。您只需使用 Spring Data for Pivotal GemFire 的**新** @EnableGemFireAsLastResource 注解和 Spring 的 事务管理基础设施和 Spring Data for Pivotal GemFire 的 @EnableGemFireAsLastResource 注解配置的组合来注解您的 Spring @Configuration 类即可。
配置如下…
@Configuration
@EnableGemFireAsLastResource
@EnableTransactionManagement(order = 1)
class GeodeConfiguration {
...
}
唯一的要求是…
3.1) @EnableGemFireAsLastResource 注解必须与 Spring 的 @EnableTransactionManagement 注解在同一个 Spring @Configuration 类上声明。
3.2) @EnableTransactionManagement 注解的 order 属性必须显式设置为非 Integer.MAX_VALUE 或 Integer.MIN_VALUE 的整数值(默认为 Integer.MAX_VALUE)。
当然,希望您已经知道,在使用 JTA 事务时,您还需要配置 Spring 的 JtaTransactionManager,如下所示:
@Bean
public JtaTransactionManager transactionManager(UserTransaction userTransaction) {
JtaTransactionManager transactionManager = new JtaTransactionManager();
transactionManager.setUserTransaction(userTransaction);
return transactionManager;
}
部分本地缓存事务管理中的配置**不**适用于此处。Spring Data for Pivotal GemFire 的 GemfireTransactionManager 的使用适用于“仅本地”缓存事务,**不**适用于“全局”JTA 事务。因此,在这种情况下,您**不**配置 SDG GemfireTransactionManager。您配置 Spring 的 JtaTransactionManager,如上所示。 |
有关将 *Spring 的事务管理*与 JTA 结合使用的更多详细信息,请参阅此处。
实际上,Spring Data for Pivotal GemFire 的 @EnableGemFireAsLastResource 注解导入了包含 2 个 Aspect bean 定义的配置,这些定义在事务操作期间的适当点处理 Pivotal GemFire o.a.g.ra.GFConnectionFactory.getConnection() 和 o.a.g.ra.GFConnection.close() 操作。
具体来说,正确的事件顺序如下
-
jtaTransaction.begin() -
GFConnectionFactory.getConnection() -
调用应用程序的
@Transactional服务方法 -
或者
jtaTransaction.commit()或者jtaTransaction.rollback() -
最后,
GFConnection.close()
这与您作为应用程序开发人员,如果必须自己使用 JTA API + Pivotal GemFire API 时手动编写代码的方式一致,如 Pivotal GemFire 的示例所示。
幸好,Spring 为您做了繁重的工作,您只需在应用了适当的配置(如上所示)后执行以下操作:
@Service
class MyTransactionalService {
@Transactional
public <Return-Type> someTransactionalServiceMethod() {
// perform business logic interacting with and accessing multiple JTA resources atomically
}
...
}
一旦您的应用程序进入 @Transactional 边界(即调用 MyTransactionService.someTransactionalServiceMethod() 时),Spring 基于 JTA 的 PlatformTransactionManager 会为您适当处理上述 #1 和 #4。
#2 和 #3 由 Spring Data for Pivotal GemFire 的新切面处理,这些切面通过 @EnableGemFireAsLastResource 注解启用。
当然,#3 是您的应用程序的责任。
事实上,如果配置了适当的日志记录,您将看到正确的事件序列……
2017-Jun-22 11:11:37 TRACE TransactionInterceptor - Getting transaction for [example.app.service.MessageService.send]
2017-Jun-22 11:11:37 TRACE GemFireAsLastResourceConnectionAcquiringAspect - Acquiring {data-store-name} Connection
from {data-store-name} JCA ResourceAdapter registered at [gfe/jca]
2017-Jun-22 11:11:37 TRACE MessageService - PRODUCER [ Message :
[{ @type = example.app.domain.Message, id= MSG0000000000, message = SENT }],
JSON : [{"id":"MSG0000000000","message":"SENT"}] ]
2017-Jun-22 11:11:37 TRACE TransactionInterceptor - Completing transaction for [example.app.service.MessageService.send]
2017-Jun-22 11:11:37 TRACE GemFireAsLastResourceConnectionClosingAspect - Closed {data-store-name} Connection @ [Reference [...]]
有关使用 Pivotal GemFire 缓存级事务的更多详细信息,请参阅此处。
有关在 JTA 事务中使用 Pivotal GemFire 的更多详细信息,请参阅此处。
有关将 Pivotal GemFire 配置为“Last Resource”的更多详细信息,请参阅此处。
7.5. TransactionEventListener
使用事务时,可能需要注册一个监听器以在事务提交之前或之后执行某些操作,或在回滚发生后执行某些操作。
Spring Data for Pivotal GemFire 通过 @TransactionalEventListener 注解,使得创建将在事务特定阶段调用的监听器变得容易。使用 @TransactionalEventListener 注解的方法(如下所示)将在指定的 phase 期间收到从事务方法发布的事件。
@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void handleAfterCommit(MyEvent event) {
// do something after transaction is committed
}
为了调用上述方法,您必须在事务中发布一个事件,如下所示:
@Service
class MyTransactionalService {
@Autowired
private final ApplicationEventPublisher applicationEventPublisher;
@Transactional
public <Return-Type> someTransactionalServiceMethod() {
// Perform business logic interacting with and accessing multiple transactional resources atomically, then...
applicationEventPublisher.publishEvent(new MyEvent(...));
}
...
}
@TransactionalEventListener 注解允许您指定事件处理方法将被调用的事务 phase。选项包括:AFTER_COMMIT、AFTER_COMPLETION、AFTER_ROLLBACK 和 BEFORE_COMMIT。如果未指定,phase 默认为 AFTER_COMMIT。如果您希望即使没有事务也调用监听器,您可以将 fallbackExecution 设置为 true。
7.6. 连续查询(CQ)
Pivotal GemFire 提供的一个强大功能是连续查询(或 CQ)。
简而言之,CQ 允许开发人员创建和注册一个 OQL 查询,然后在添加到 Pivotal GemFire 的新数据与查询谓词匹配时自动收到通知。Spring Data for Pivotal GemFire 通过 org.springframework.data.gemfire.listener 包及其监听器容器提供对 CQ 的专门支持;其功能和命名与 Spring Framework 中的 JMS 集成非常相似;事实上,熟悉 Spring 中 JMS 支持的用户会感到非常熟悉。
基本上,Spring Data for Pivotal GemFire 允许 POJO 上的方法成为 CQ 的端点。只需定义查询并指示应调用的方法,以便在匹配时收到通知。Spring Data for Pivotal GemFire 会处理其余部分。这与 Java EE 的消息驱动 bean 样式非常相似,但没有任何基于 Pivotal GemFire 的基类或接口实现要求。
| 目前,连续查询仅在 Pivotal GemFire 的客户端/服务器拓扑中受支持。此外,所使用的客户端池需要启用订阅。请参阅 Pivotal GemFire 文档以获取更多信息。 |
7.6.1. 连续查询监听器容器
Spring Data for Pivotal GemFire 通过使用 SDG 的 ContinuousQueryListenerContainer 来处理 CQ 周围的基础设施,从而简化了 CQ 事件的创建、注册、生命周期和分派,它为用户做了所有繁重的工作。熟悉 EJB 和 JMS 的用户会发现这些概念很熟悉,因为它被设计成尽可能接近 Spring Framework 及其消息驱动 POJO (MDP) 中提供的支持。
SDG ContinuousQueryListenerContainer 充当事件(或消息)监听器容器;它用于接收来自已注册 CQ 的事件,并调用注入到其中的 POJO。监听器容器负责所有消息接收线程并将消息分派到监听器进行处理。它充当 EDP(事件驱动 POJO)和事件提供者之间的中介,并负责 CQ 的创建和注册(以接收事件)、资源获取和释放、异常转换等。这允许您作为应用程序开发人员编写与接收事件(并对其做出反应)相关的(可能复杂的)业务逻辑,并将样板 Pivotal GemFire 基础设施问题委托给框架。
监听器容器是完全可定制的。开发人员可以选择使用 CQ 线程执行分派(同步交付)或使用新线程(来自现有池)实现异步方法,通过定义合适的 java.util.concurrent.Executor(或 Spring 的 TaskExecutor)。根据负载、监听器数量或运行时环境,开发人员应更改或调整执行器以更好地满足其需求。特别是在受管环境(如应用服务器)中,强烈建议选择合适的 TaskExecutor 以利用其运行时。
7.6.2. ContinuousQueryListener 和 ContinuousQueryListenerAdapter
ContinuousQueryListenerAdapter 类是 Spring Data for Pivotal GemFire CQ 支持的最后一个组件。简而言之,该类允许您将几乎任何实现类公开为 EDP,且限制最少。ContinuousQueryListenerAdapter 实现了 ContinuousQueryListener 接口,这是一个简单的监听器接口,类似于 Pivotal GemFire 的CqListener。
考虑以下接口定义。请注意各种事件处理方法及其参数
public interface EventDelegate {
void handleEvent(CqEvent event);
void handleEvent(Operation baseOp);
void handleEvent(Object key);
void handleEvent(Object key, Object newValue);
void handleEvent(Throwable throwable);
void handleQuery(CqQuery cq);
void handleEvent(CqEvent event, Operation baseOp, byte[] deltaValue);
void handleEvent(CqEvent event, Operation baseOp, Operation queryOp, Object key, Object newValue);
}
package example;
class DefaultEventDelegate implements EventDelegate {
// implementation elided for clarity...
}
特别要注意的是,上述 EventDelegate 接口的实现完全没有 Pivotal GemFire 依赖。它确实是一个 POJO,我们可以并且将通过以下配置将其转化为 EDP。
| 该类不必实现接口;接口仅用于更好地展示契约与实现之间的解耦。 |
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
">
<gfe:client-cache/>
<gfe:pool subscription-enabled="true">
<gfe:server host="localhost" port="40404"/>
</gfe:pool>
<gfe:cq-listener-container>
<!-- default handle method -->
<gfe:listener ref="listener" query="SELECT * FROM /SomeRegion"/>
<gfe:listener ref="another-listener" query="SELECT * FROM /AnotherRegion" name="myQuery" method="handleQuery"/>
</gfe:cq-listener-container>
<bean id="listener" class="example.DefaultMessageDelegate"/>
<bean id="another-listener" class="example.DefaultMessageDelegate"/>
...
<beans>
上面的示例展示了监听器可以具有的几种不同形式;最少需要监听器引用和实际查询定义。然而,可以为生成的连续查询指定一个名称(用于监控很有用),也可以指定方法名称(默认为 handleEvent)。指定的方法可以有各种参数类型,EventDelegate 接口列出了允许的类型。 |
上面的示例使用 Spring Data for Pivotal GemFire 命名空间声明事件监听器容器并自动注册监听器。完整的bean定义如下所示:
<!-- this is the Event Driven POJO (MDP) -->
<bean id="eventListener" class="org.springframework.data.gemfire.listener.adapter.ContinuousQueryListenerAdapter">
<constructor-arg>
<bean class="gemfireexample.DefaultEventDelegate"/>
</constructor-arg>
</bean>
<!-- and this is the event listener container... -->
<bean id="gemfireListenerContainer" class="org.springframework.data.gemfire.listener.ContinuousQueryListenerContainer">
<property name="cache" ref="gemfireCache"/>
<property name="queryListeners">
<!-- set of CQ listeners -->
<set>
<bean class="org.springframework.data.gemfire.listener.ContinuousQueryDefinition" >
<constructor-arg value="SELECT * FROM /SomeRegion" />
<constructor-arg ref="eventListener"/>
</bean>
</set>
</property>
</bean>
每次收到事件时,适配器都会在 Pivotal GemFire 事件和所需方法参数之间自动透明地执行类型转换。由方法调用引起的任何异常都会被容器捕获并处理(默认情况下,会被记录)。
7.7. 连接 Declarable 组件
Pivotal GemFire XML 配置(通常称为 cache.xml)允许将用户对象声明为配置的一部分。通常,这些对象是 CacheLoaders 或 Pivotal GemFire 支持的其他可插拔回调组件。使用原生的 Pivotal GemFire 配置,通过 XML 声明的每个用户类型都必须实现 Declarable 接口,该接口允许通过 Properties 实例将任意参数传递给声明的类。
在本节中,我们将描述如何在 cache.xml 中定义这些可插拔组件时使用 Spring 进行配置,同时将您的缓存/区域配置保留在 cache.xml 中。这使得您的可插拔组件能够专注于应用程序逻辑,而不是 DataSources 或其他协作器的位置或创建。
但是,如果您正在启动一个新项目,建议您直接在 Spring 中配置缓存、区域和其他可插拔的 Pivotal GemFire 组件。这样可以避免继承 Declarable 接口或本节中介绍的基类。
有关此方法的更多信息,请参阅以下侧边栏。
作为使用 Spring 配置 Declarable 组件的示例,考虑以下声明(取自 Declarable Javadoc)
<cache-loader>
<class-name>com.company.app.DBLoader</class-name>
<parameter name="URL">
<string>jdbc://12.34.56.78/mydb</string>
</parameter>
</cache-loader>
为了简化参数解析、转换和对象初始化任务,Spring Data for Pivotal GemFire 提供了一个基类 (WiringDeclarableSupport),它允许通过模板 bean 定义来连接 Pivotal GemFire 用户对象,或者在缺少模板 bean 定义的情况下,通过 Spring IoC 容器执行自动连接。为了利用此功能,用户对象需要扩展 WiringDeclarableSupport,它会自动定位声明的 BeanFactory,并作为初始化过程的一部分执行连接。
7.7.1. 使用模板bean定义进行配置
使用时,WiringDeclarableSupport 会首先尝试定位现有 bean 定义并将其用作连接模板。除非另行指定,否则组件类名将用作隐式 bean 定义名称。
让我们看看在这种情况下 DBLoader 声明会是什么样子
class DBLoader extends WiringDeclarableSupport implements CacheLoader {
private DataSource dataSource;
public void setDataSource(DataSource dataSource){
this.dataSource = dataSource;
}
public Object load(LoaderHelper helper) { ... }
}
<cache-loader>
<class-name>com.company.app.DBLoader</class-name>
<!-- no parameter is passed (use the bean's implicit name, which is the class name) -->
</cache-loader>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="dataSource" ... />
<!-- template bean definition -->
<bean id="com.company.app.DBLoader" abstract="true" p:dataSource-ref="dataSource"/>
</beans>
在上述场景中,由于未指定任何参数,因此将 ID/名称为 com.company.app.DBLoader 的 bean 用作连接 Pivotal GemFire 创建的实例的模板。对于 bean 名称使用不同约定的情况,可以在 Pivotal GemFire 配置中传入 bean-name 参数
<cache-loader>
<class-name>com.company.app.DBLoader</class-name>
<!-- pass the bean definition template name as parameter -->
<parameter name="bean-name">
<string>template-bean</string>
</parameter>
</cache-loader>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
">
<bean id="dataSource" ... />
<!-- template bean definition -->
<bean id="template-bean" abstract="true" p:dataSource-ref="dataSource"/>
</beans>
| 模板 bean 定义不必在 XML 中声明。允许任何格式(Groovy、注解等)。 |
7.7.2. 使用自动装配和注解进行配置
默认情况下,如果未找到 bean 定义,WiringDeclarableSupport 将自动装配声明实例。这意味着,除非实例提供了任何依赖注入元数据,否则容器将找到对象设置器并尝试自动满足这些依赖项。但是,开发人员也可以使用 JDK 5 注解为自动装配过程提供额外信息。
| 我们强烈建议阅读 Spring 文档中专门的章节,以获取有关受支持注解和启用因素的更多信息。 |
例如,上面假设的 DBLoader 声明可以通过以下方式注入 Spring 配置的 DataSource
class DBLoader extends WiringDeclarableSupport implements CacheLoader {
// use annotations to 'mark' the needed dependencies
@javax.inject.Inject
private DataSource dataSource;
public Object load(LoaderHelper helper) { ... }
}
<cache-loader>
<class-name>com.company.app.DBLoader</class-name>
<!-- no need to declare any parameters since the class is auto-wired -->
</cache-loader>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd
">
<!-- enable annotation processing -->
<context:annotation-config/>
</beans>
通过使用 JSR-330 注解,CacheLoader 代码得到了简化,因为 DataSource 的位置和创建已外部化,并且用户代码只关注加载过程。DataSource 可能是事务性的,延迟创建的,在多个对象之间共享的,或者从 JNDI 检索的。这些方面可以很容易地通过 Spring 容器进行配置和更改,而无需修改 DBLoader 代码。
7.8. 支持 Spring 缓存抽象
Spring Data for Pivotal GemFire 提供了 Spring 缓存抽象的实现,将 Pivotal GemFire 定位为 Spring 缓存基础设施中的缓存提供者。
要将 Pivotal GemFire 用作后端实现,即 Spring 缓存抽象中的“缓存提供者”,只需将 GemfireCacheManager 添加到您的配置中
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache https://www.springframework.org/schema/cache/spring-cache.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
">
<!-- enable declarative caching -->
<cache:annotation-driven/>
<gfe:cache id="gemfire-cache"/>
<!-- declare GemfireCacheManager; must have a bean ID of 'cacheManager' -->
<bean id="cacheManager" class="org.springframework.data.gemfire.cache.GemfireCacheManager"
p:cache-ref="gemfire-cache">
</beans>
如果使用默认的缓存 bean 名称(即“gemfireCache”),即没有显式 ID 的 <gfe:cache>,则 CacheManager bean 定义上的 cache-ref 属性不是必需的。 |
当声明 GemfireCacheManager (Singleton) bean 实例并启用声明式缓存时(无论是使用 <cache:annotation-driven/> 的 XML 配置还是使用 Spring 的 @EnableCaching 注解的 JavaConfig),Spring 缓存注解(例如 @Cacheable)会标识将使用 Pivotal GemFire 区域在内存中缓存数据的“缓存”。
这些缓存(即区域)必须在使用它们的缓存注解之前存在,否则会发生错误。
举个例子,假设您有一个客户服务应用程序,其中包含一个执行缓存的 CustomerService 应用程序组件……
@Service
class CustomerService {
@Cacheable(cacheNames="Accounts", key="#customer.id")
Account createAccount(Customer customer) {
...
}
那么您将需要以下配置。
XML
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:gfe="https://www.springframework.org/schema/gemfire"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/cache https://www.springframework.org/schema/cache/spring-cache.xsd
https://www.springframework.org/schema/gemfire https://www.springframework.org/schema/gemfire/spring-gemfire.xsd
">
<!-- enable declarative caching -->
<cache:annotation-driven/>
<bean id="cacheManager" class="org.springframework.data.gemfire.cache.GemfireCacheManager">
<gfe:cache/>
<gfe:partitioned-region id="accountsRegion" name="Accounts" persistent="true" ...>
...
</gfe:partitioned-region>
</beans>
JavaConfig
@Configuration
@EnableCaching
class ApplicationConfiguration {
@Bean
CacheFactoryBean gemfireCache() {
return new CacheFactoryBean();
}
@Bean
GemfireCacheManager cacheManager() {
GemfireCacheManager cacheManager = GemfireCacheManager();
cacheManager.setCache(gemfireCache());
return cacheManager;
}
@Bean("Accounts")
PartitionedRegionFactoryBean accountsRegion() {
PartitionedRegionFactoryBean accounts = new PartitionedRegionFactoryBean();
accounts.setCache(gemfireCache());
accounts.setClose(false);
accounts.setPersistent(true);
return accounts;
}
}
当然,您可以自由选择任何您喜欢的区域类型(例如 REPLICATE、PARTITION、LOCAL 等)。
有关 Spring 缓存抽象的更多详细信息,请再次参阅文档。
8. 使用 Pivotal GemFire 序列化
为了提高 Pivotal GemFire 内存数据网格的整体性能,Pivotal GemFire 支持一种专用的序列化协议,称为 PDX,它比标准 Java 序列化更快,提供更紧凑的结果,并且可以在各种语言平台(Java、C++ 和 .NET)上透明地工作。
有关更多详细信息,请参阅PDX 序列化功能和PDX 序列化内部结构。
本章讨论 Spring Data for Pivotal GemFire 简化和改进 Pivotal GemFire 在 Java 中自定义序列化的各种方式。
8.1. 连接反序列化实例
序列化对象通常具有瞬态数据。瞬态数据通常取决于其在特定时间点所在的系统或环境。例如,DataSource 是环境特定的。序列化此类信息是无用的,甚至可能危险,因为它仅限于特定的 VM 或机器。对于此类情况,Spring Data for Pivotal GemFire 提供了一个特殊的Instantiator,它为 Pivotal GemFire 在反序列化期间创建的每个新实例执行连接。
通过这种机制,您可以依靠 Spring 容器注入和管理某些依赖项,从而轻松地将瞬态数据与持久化数据分离,并以透明的方式拥有丰富的领域对象。
Spring 用户可能会发现这种方法类似于 @Configurable 的方法。WiringInstantiator 的工作方式类似于 WiringDeclarableSupport,它会首先尝试定位一个 bean 定义作为连接模板,否则会回退到自动连接。
有关连接功能的更多详细信息,请参阅上一节(连接 Declarable 组件)。
要使用 SDG Instantiator,请将其声明为一个 bean,如以下示例所示:
<bean id="instantiator" class="org.springframework.data.gemfire.serialization.WiringInstantiator">
<!-- DataSerializable type -->
<constructor-arg>org.pkg.SomeDataSerializableClass</constructor-arg>
<!-- type id -->
<constructor-arg>95</constructor-arg>
</bean>
在 Spring 容器启动期间,一旦它被初始化,Instantiator 默认情况下会向 Pivotal GemFire 序列化系统注册自己,并对 Pivotal GemFire 在反序列化期间创建的 SomeDataSerializableClass 的所有实例执行连接。
8.2. 自动生成自定义 Instantiators
对于数据密集型应用程序,当数据流入时,每台机器上可能会创建大量实例。Pivotal GemFire 使用反射来创建新类型,但在某些情况下,这可能会非常昂贵。一如既往,最好进行性能分析以量化是否存在这种情况。对于此类情况,Spring Data for Pivotal GemFire 允许自动生成 Instatiator 类,这些类实例化新类型(使用默认构造函数)而无需使用反射。以下示例演示如何创建实例化器
<bean id="instantiatorFactory" class="org.springframework.data.gemfire.serialization.InstantiatorFactoryBean">
<property name="customTypes">
<map>
<entry key="org.pkg.CustomTypeA" value="1025"/>
<entry key="org.pkg.CustomTypeB" value="1026"/>
</map>
</property>
</bean>
上述定义自动为两个类(CustomTypeA 和 CustomTypeB)生成两个 Instantiators,并将其在用户 ID 1025 和 1026 下注册到 Pivotal GemFire。这两个 Instantiators 避免使用反射,并直接通过 Java 代码创建实例。
9. POJO 映射
本节内容
9.1. 对象映射基础
本节涵盖 Spring Data 对象映射、对象创建、字段和属性访问、可变性与不可变性的基础知识。请注意,本节仅适用于不使用底层数据存储(如 JPA)对象映射的 Spring Data 模块。此外,请务必查阅存储特定章节,了解存储特定对象映射,例如索引、自定义列或字段名称等。
Spring Data 对象映射的核心职责是创建领域对象实例,并将存储原生数据结构映射到这些实例上。这意味着我们需要两个基本步骤
-
通过使用公开的构造函数之一创建实例。
-
实例填充以具体化所有公开的属性。
9.1.1. 对象创建
Spring Data 会自动尝试检测持久化实体的构造函数,该构造函数将用于具体化该类型的对象。解析算法的工作方式如下
-
如果存在无参构造函数,将使用它。其他构造函数将被忽略。
-
如果存在单个带参数的构造函数,将使用它。
-
如果存在多个带参数的构造函数,则 Spring Data 将使用的构造函数必须使用
@PersistenceConstructor进行注解。
值解析假定构造函数参数名与实体的属性名匹配,即解析将按照属性将要填充的方式执行,包括映射中的所有自定义(不同的数据存储列或字段名等)。这还要求类文件中提供参数名信息,或者构造函数上存在 @ConstructorProperties 注解。
值解析可以通过使用 Spring Framework 的 @Value 值注解和存储特定的 SpEL 表达式进行自定义。请查阅有关存储特定映射的部分以获取更多详细信息。
9.1.2. 属性填充
一旦创建了实体实例,Spring Data 会填充该类的所有剩余持久化属性。除非已由实体的构造函数填充(即通过其构造函数参数列表消耗),否则将首先填充标识符属性,以允许解析循环对象引用。之后,所有尚未由构造函数填充的非瞬态属性将在实体实例上设置。为此,我们使用以下算法
-
如果属性是不可变的但公开了一个 wither 方法(见下文),我们使用 wither 创建一个具有新属性值的新实体实例。
-
如果定义了属性访问(即通过 getter 和 setter 访问),我们将调用 setter 方法。
-
默认情况下,我们直接设置字段值。
让我们看看以下实体
class Person {
private final @Id Long id; (1)
private final String firstname, lastname; (2)
private final LocalDate birthday;
private final int age; (3)
private String comment; (4)
private @AccessType(Type.PROPERTY) String remarks; (5)
static Person of(String firstname, String lastname, LocalDate birthday) { (6)
return new Person(null, firstname, lastname, birthday,
Period.between(birthday, LocalDate.now()).getYears());
}
Person(Long id, String firstname, String lastname, LocalDate birthday, int age) { (6)
this.id = id;
this.firstname = firstname;
this.lastname = lastname;
this.birthday = birthday;
this.age = age;
}
Person withId(Long id) { (1)
return new Person(id, this.firstname, this.lastname, this.birthday, this.age);
}
void setRemarks(String remarks) { (5)
this.remarks = remarks;
}
}
| 1 | 标识符属性是 final 的,但在构造函数中设置为 null。该类公开了一个 withId(…) 方法,用于设置标识符,例如当一个实例插入到数据存储中并生成了标识符时。原始的 Person 实例保持不变,因为创建了一个新实例。相同的模式通常适用于其他由存储管理但可能需要更改以进行持久化操作的属性。 |
| 2 | firstname 和 lastname 属性是普通的不可变属性,可能通过 getter 公开。 |
| 3 | age 属性是不可变的,但由 birthday 属性派生。按照所示设计,数据库值将优先于默认值,因为 Spring Data 使用唯一声明的构造函数。即使目的是优先计算,重要的是此构造函数也接受 age 作为参数(可能忽略它),否则属性填充步骤将尝试设置 age 字段,并因其不可变且不存在 wither 而失败。 |
| 4 | comment 属性是可变的,并通过直接设置其字段进行填充。 |
| 5 | remarks 属性是可变的,通过直接设置 comment 字段或调用 setter 方法进行填充 |
| 6 | 该类公开了一个工厂方法和一个用于对象创建的构造函数。核心思想是使用工厂方法而不是额外的构造函数,以避免通过 @PersistenceConstructor 进行构造函数消歧的需要。相反,属性的默认值处理在工厂方法中进行。 |
9.1.3. 一般建议
-
尽量坚持使用不可变对象 — 不可变对象创建起来很简单,因为实例化一个对象就只剩下调用其构造函数了。此外,这避免了您的领域对象中充斥着允许客户端代码操作对象状态的 setter 方法。如果您需要这些方法,最好将它们设为包保护,以便只能由有限数量的协同定位类型调用。仅限构造函数的实例化比属性填充快 30%。
-
提供一个全参构造函数 — 即使您不能或不想将您的实体建模为不可变值,提供一个接受实体所有属性(包括可变属性)作为参数的构造函数仍然很有价值,因为这允许对象映射跳过属性填充以获得最佳性能。
-
使用工厂方法而不是重载构造函数以避免
@PersistenceConstructor— 由于需要一个全参构造函数以获得最佳性能,我们通常希望公开更多特定于应用程序用例的构造函数,这些构造函数会省略诸如自动生成标识符等内容。使用静态工厂方法来公开这些全参构造函数的变体是一种成熟的模式。 -
确保您遵守允许使用生成的实例化器和属性访问器类的约束 —
-
对于要生成的标识符,仍然使用 final 字段与 wither 方法相结合 —
-
使用 Lombok 避免样板代码 — 由于持久化操作通常需要一个接受所有参数的构造函数,它们的声明变成了繁琐的样板参数到字段赋值的重复,最好通过使用 Lombok 的
@AllArgsConstructor来避免。
9.1.4. Kotlin 支持
Spring Data 适应 Kotlin 的特性,以允许对象创建和修改。
Kotlin 对象创建
Kotlin 类支持实例化,所有类默认都是不可变的,并且需要显式属性声明来定义可变属性。考虑以下 data 类 Person
data class Person(val id: String, val name: String)
上述类编译为带有显式构造函数的典型类。我们可以通过添加另一个构造函数并使用 @PersistenceConstructor 注解来定制这个类,以指示构造函数偏好
data class Person(var id: String, val name: String) {
@PersistenceConstructor
constructor(id: String) : this(id, "unknown")
}
Kotlin 通过允许在未提供参数时使用默认值来支持参数可选性。当 Spring Data 检测到带有参数默认值的构造函数时,如果数据存储未提供值(或简单地返回 null),它会使这些参数缺失,以便 Kotlin 可以应用参数默认值。考虑以下对 name 应用参数默认值的类
data class Person(var id: String, val name: String = "unknown")
每次 name 参数不在结果中或其值为 null 时,name 都会默认为 unknown。
Kotlin 数据类的属性填充
在 Kotlin 中,所有类默认都是不可变的,并且需要显式属性声明来定义可变属性。考虑以下 data 类 Person
data class Person(val id: String, val name: String)
这个类实际上是不可变的。它允许创建新实例,因为 Kotlin 会生成一个 copy(…) 方法,该方法会创建新对象实例,复制现有对象的所有属性值,并应用作为方法参数提供的属性值。
9.2. 实体映射
Spring Data for Pivotal GemFire 提供对存储在区域中的实体进行映射的支持。映射元数据通过在应用程序域类上使用注解来定义,如以下示例所示
@Region("People")
public class Person {
@Id Long id;
String firstname;
String lastname;
@PersistenceConstructor
public Person(String firstname, String lastname) {
// …
}
…
}
@Region 注解可用于自定义存储 Person 类实例的区域。@Id 注解可用于注解应作为缓存区域键的属性,以标识区域条目。@PersistenceConstructor 注解有助于消除多个可能可用的带参数构造函数的歧义,并明确标记被注解的构造函数为用于构造实体的构造函数。在没有或只有一个构造函数的应用程序域类中,您可以省略该注解。
除了将实体存储在顶级区域中之外,实体还可以存储在子区域中,如以下示例所示
@Region("/Users/Admin")
public class Admin extends User {
…
}
@Region("/Users/Guest")
public class Guest extends User {
…
}
请务必使用 Pivotal GemFire 区域的完整路径,如通过 <*-region> 元素的 id 或 name 属性与 Spring Data for Pivotal GemFire XML 命名空间定义的那样。
9.2.1. 按区域类型进行实体映射
除了 @Region 注解之外,Spring Data for Pivotal GemFire 还识别特定类型的区域映射注解:@ClientRegion、@LocalRegion、@PartitionRegion 和 @ReplicateRegion。
在功能上,这些注解在 SDG 映射基础设施中与通用 @Region 注解完全相同。然而,这些额外的映射注解在 Spring Data for Pivotal GemFire 的注解配置模型中很有用。当与 Spring @Configuration 注解类上的 @EnableEntityDefinedRegions 配置注解结合使用时,可以在本地缓存中生成区域,无论应用程序是客户端还是对等体。
这些注解让您能够更具体地指定您的应用程序实体类应映射到哪种类型的区域,并且还会影响区域的数据管理策略(例如,分区——也称为分片——与复制数据)。
将这些特定类型的区域映射注解与 SDG 注解配置模型一起使用,可以免去您在配置中明确定义这些区域的麻烦。
9.3. 仓库映射
作为在实体类上使用 @Region 注解指定实体存储区域的替代方法,您也可以在实体的 Repository 接口上指定 @Region 注解。有关更多详细信息,请参阅Spring Data for Pivotal GemFire 仓库。
然而,假设您想将 Person 记录存储在多个 Pivotal GemFire 区域中(例如,People 和 Customers)。那么您可以按如下方式定义相应的 Repository 接口扩展
@Region("People")
public interface PersonRepository extends GemfireRepository<Person, String> {
…
}
@Region("Customers")
public interface CustomerRepository extends GemfireRepository<Person, String> {
...
}
然后,通过单独使用每个 Repository,您可以将实体存储在多个 Pivotal GemFire 区域中,如以下示例所示
@Service
class CustomerService {
CustomerRepository customerRepo;
PersonRepository personRepo;
Customer update(Customer customer) {
customerRepo.save(customer);
personRepo.save(customer);
return customer;
}
您甚至可以将 update 服务方法包装在 Spring 管理的事务中,无论是本地缓存事务还是全局事务。
9.4. MappingPdxSerializer
Spring Data for Pivotal GemFire 提供了一个自定义的 PdxSerializer 实现,名为 MappingPdxSerializer,它使用 Spring Data 映射元数据来定制实体序列化。
该序列化器还允许您通过使用 Spring Data EntityInstantiator 抽象来自定义实体实例化。默认情况下,该序列化器使用 ReflectionEntityInstantiator,它使用映射实体的持久化构造函数。持久化构造函数可以是默认构造函数、单独声明的构造函数或显式用 @PersistenceConstructor 注解的构造函数。
为了为构造函数参数提供参数,序列化器从提供的 PdxReader 读取具有命名构造函数参数(通过 Spring 的 @Value 注解显式标识)的字段,如以下示例所示
@Valuepublic class Person {
public Person(@Value("#root.thing") String firstName, @Value("bean") String lastName) {
…
}
}
以这种方式注解的实体类会从 PdxReader 中读取“thing”字段,并将其作为构造函数参数 firstname 的参数值传递。lastName 的值是一个名为“bean”的 Spring bean。
除了 EntityInstantiators 提供的自定义实例化逻辑和策略之外,MappingPdxSerializer 还提供了远超 Pivotal GemFire 自己的 ReflectionBasedAutoSerializer 的功能。
虽然 Pivotal GemFire 的 ReflectionBasedAutoSerializer 方便地使用 Java 反射来填充实体,并使用正则表达式来识别应由序列化器处理(序列化和反序列化)的类型,但它无法像 MappingPdxSerializer 那样执行以下操作
-
根据实体字段或属性名称和类型注册自定义
PdxSerializer对象。 -
方便地识别 ID 属性。
-
自动处理只读属性。
-
自动处理瞬态属性。
-
以空值和类型安全的方式允许更健壮的类型过滤(例如,不限于仅使用正则表达式表示类型)。
我们现在将更详细地探讨 MappingPdxSerializer 的每个功能。
9.4.1. 自定义 PdxSerializer 注册
MappingPdxSerializer 允许您根据实体的字段或属性名称和类型注册自定义 PdxSerializers。
例如,假设您定义了一个建模 User 的实体类型,如下所示
package example.app.security.auth.model;
public class User {
private String name;
private Password password;
...
}
虽然用户的姓名可能不需要任何特殊的逻辑来序列化该值,但另一方面,序列化密码可能需要额外的逻辑来处理字段或属性的敏感性质。
或许您想在客户端和服务器之间通过网络发送密码值时,除了 TLS 之外,还要保护密码,并且您只想存储加盐的哈希值。使用 MappingPdxSerializer 时,您可以注册一个自定义的 PdxSerializer 来处理用户密码,如下所示
PdxSerializersMap<?, PdxSerializer> customPdxSerializers = new HashMap<>();
customPdxSerializers.put(Password.class, new SaltedHashPasswordPdxSerializer());
mappingPdxSerializer.setCustomPdxSerializers(customPdxSerializers);
在将应用程序定义的 SaltedHashPasswordPdxSerializer 实例注册到 Password 应用程序域模型类型之后,MappingPdxSerializer 将咨询自定义 PdxSerializer 来序列化和反序列化所有 Password 对象,无论其包含对象是什么(例如 User)。
然而,假设您只想在 User 对象上自定义 Passwords 的序列化。为此,您可以通过指定 Class 字段或属性的完全限定名称来注册 User 类型的自定义 PdxSerializer,如以下示例所示
PdxSerializersMap<?, PdxSerializer> customPdxSerializers = new HashMap<>();
customPdxSerializers.put("example.app.security.auth.model.User.password", new SaltedHashPasswordPdxSerializer());
mappingPdxSerializer.setCustomPdxSerializers(customPdxSerializers);
请注意使用完全限定的字段或属性名称(即 example.app.security.auth.model.User.password)作为自定义 PdxSerializer 注册键。
您可以使用更具逻辑性的代码片段来构造注册键,例如:User.class.getName().concat(".password");。我们推荐这种方式而不是前面所示的示例。前面的示例试图尽可能明确地表达注册的语义。 |
9.4.2. 映射 ID 属性
与 Pivotal GemFire 的 ReflectionBasedAutoSerializer 类似,SDG 的 MappingPdxSerializer 也能够确定实体的标识符。但是,MappingPdxSerializer 通过使用 Spring Data 的映射元数据来做到这一点,具体来说是通过使用 Spring Data 的 @Id 注解查找指定为标识符的实体属性。或者,任何名为“id”且未明确使用 @Id 注解的字段或属性也被指定为实体的标识符。
例如:
class Customer {
@Id
Long id;
...
}
在这种情况下,Customer 的 id 字段被标记为 PDX 类型元数据中的标识符字段,方法是在序列化期间调用 PdxSerializer.toData(..) 方法时使用 PdxWriter.markIdentifierField(:String)。
9.4.3. 映射只读属性
当您的实体定义只读属性时会发生什么?
首先,理解“只读”属性是什么很重要。如果您按照 JavaBeans 规范(与 Spring 一样)定义 POJO,您可能会定义一个带有只读属性的 POJO,如下所示
package example;
class ApplicationDomainType {
private AnotherType readOnly;
public AnotherType getReadOnly() [
this.readOnly;
}
...
}
readOnly 属性是只读的,因为它不提供 setter 方法。它只有 getter 方法。在这种情况下,readOnly 属性(不要与 readOnly DomainType 字段混淆)被认为是只读的。
因此,MappingPdxSerializer 在反序列化期间调用 PdxSerializer.fromData(:Class<ApplicationDomainType>, :PdxReader) 方法时,不会尝试为该属性设置值,特别是在 PDX 序列化字节中存在值的情况下。
这在某些情况下很有用,例如您可能返回某个实体类型的视图或投影,并且只想设置可写状态。也许实体的视图或投影是基于授权或其他条件。关键是,您可以根据应用程序的用例和需求,适当地利用此功能。如果您希望字段或属性始终被写入,只需定义一个 setter 方法即可。
9.4.4. 映射瞬态属性
同样,当您的实体定义了 transient 属性时会发生什么?
您会期望您的实体的 transient 字段或属性在序列化实体时不会序列化到 PDX。这正是发生的情况,与 Pivotal GemFire 自己的 ReflectionBasedAutoSerializer 不同,后者会序列化通过 Java 反射从对象访问的所有内容。
MappingPdxSerializer 不会序列化任何被限定为瞬态的字段或属性,无论是使用 Java 自己的 transient 关键字(在类实例字段的情况下)还是在字段或属性上使用 @Transient Spring Data 注解。
例如,您可能会定义一个具有瞬态字段和属性的实体,如下所示
package example;
class Process {
private transient int id;
private File workingDirectory;
private String name;
private Type type;
@Transient
public String getHostname() {
...
}
...
}
Process 的 id 字段和可读的 hostname 属性都不会写入 PDX。
9.4.5. 按类类型过滤
与 Pivotal GemFire 的 ReflectionBasedAutoSerializer 类似,SDG 的 MappingPdxSerializer 允许您过滤序列化和反序列化对象的类型。
然而,与 Pivotal GemFire 的 ReflectionBasedAutoSerializer 使用复杂的正则表达式来表达序列化器处理的类型不同,SDG 的 MappingPdxSerializer 使用更健壮的 java.util.function.Predicate 接口和 API 来表达类型匹配标准。
如果您喜欢使用正则表达式,可以使用 Java 的正则表达式支持来实现 Predicate。 |
Java 的 Predicate 接口的优点是,您可以使用方便且适当的 API 方法来组合 Predicate,包括:and(:Predicate)、or(:Predicate) 和 negate()。
以下示例展示了 Predicate API 的实际应用
Predicate<Class<?>> customerTypes =
type -> Customer.class.getPackage().getName().startsWith(type.getName()); // Include all types in the same package as `Customer`
Predicate includedTypes = customerTypes
.or(type -> User.class.isAssignble(type)); // Additionally, include User sub-types (e.g. Admin, Guest, etc)
mappingPdxSerializer.setIncludeTypeFilters(includedTypes);
mappingPdxSerializer.setExcludeTypeFilters(
type -> !Reference.class.getPackage(type.getPackage()); // Exclude Reference types
传递给您的 Predicate 的任何 Class 对象都保证不为 null。 |
SDG 的 MappingPdxSerializer 支持包括和排除类类型过滤器。
排除类型过滤
默认情况下,SDG 的 MappingPdxSerializer 注册预定义的 Predicates,用于过滤或排除以下包中的类型
-
java.* -
com.gemstone.gemfire.* -
org.apache.geode.* -
org.springframework.*
此外,MappingPdxSerializer 在调用 PdxSerializer.toData(:Object, :PdxWriter) 时过滤 null 对象,并在调用 PdxSerializer.fromData(:Class<?>, :PdxReader) 方法时过滤 null 类类型。
添加其他类类型或整个类型包的排除非常容易,只需定义一个 Predicate 并将其添加到 MappingPdxSerializer 中,如前所示。
MappingPdxSerializer.setExcludeTypeFilters(:Predicate<Class<?>>) 方法是累加的,这意味着它使用 Predicate.and(:Predicate<Class<?>>) 方法将您的应用程序定义的类型过滤器与上面指示的现有预定义类型过滤器 Predicates 组合起来。
然而,如果您想包含一个被排除类型过滤器隐式排除的类类型(例如 java.security Principal)怎么办?请参阅包含类型过滤。
包含类型过滤
如果您想显式包含一个类类型,或者覆盖一个隐式排除应用程序所需类类型(例如 java.security.Principal,它默认被 MappingPdxSerializer 上的 java.* 包排除类型过滤器排除)的类类型过滤器,那么只需定义适当的 Predicate 并使用 MappingPdxSerializer.setIncludeTypeFilters(:Predicate<Class<?>>) 方法将其添加到序列化器中,如下所示
Predicate<Class<?>> principalTypeFilter =
type -> java.security.Principal.class.isAssignableFrom(type);
mappingPdxSerializer.setIncludeTypeFilters(principalTypeFilters);
同样,MappingPdxSerializer.setIncludeTypeFilters(:Predicate<Class<?>>) 方法与 setExcludeTypeFilters(:Predicate<Class<?>>) 类似,是累加的,因此使用 Predicate.or(:Predicate<Class<?>>) 组合任何传递的类型过滤器。这意味着您可以根据需要多次调用 setIncludeTypeFilters(:Predicate<Class<?>>)。
当存在包含类型过滤器时,MappingPdxSerializer 会根据类类型是否未被隐式排除或类类型是否被显式包含(两者中任意一个返回 true),来决定是否对类类型的实例进行反序列化。然后,该类类型的实例将被适当地序列化或反序列化。
例如,当如前所示显式注册 Predicate<Class<Principal>> 的类型过滤器时,它会抵消 java.* 包类型上的隐式排除类型过滤器。
10. Spring Data for Pivotal GemFire 仓库
Spring Data for Pivotal GemFire 提供对使用 Spring Data Repository 抽象的支持,以便轻松地将实体持久化到 Pivotal GemFire 中并执行查询。Repository 编程模型的概述请参阅此处。
10.1. Spring XML 配置
要引导 Spring Data Repositories,请使用 Spring Data for Pivotal GemFire Data 命名空间中的 <repositories/> 元素,如以下示例所示
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:gfe-data="https://www.springframework.org/schema/data/gemfire"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/data/gemfire https://www.springframework.org/schema/data/gemfire/spring-data-gemfire.xsd
">
<gfe-data:repositories base-package="com.example.acme.repository"/>
</beans>
上述配置片段会在配置的基础包下查找接口,并为这些接口创建由 SimpleGemFireRepository 支持的 Repository 实例。
| 除非您的应用程序域类正确映射到配置的区域,否则引导过程将失败。 |
10.2. 基于 Spring Java 的配置
或者,许多开发人员更喜欢使用 Spring 的基于 Java 的容器配置。
使用此方法,您可以通过使用 SDG @EnableGemfireRepositories 注解来引导 Spring Data Repositories,如以下示例所示
@EnableGemfireRepositories 引导 Spring Data for Pivotal GemFire Repositories@SpringBootApplication
@EnableGemfireRepositories(basePackages = "com.example.acme.repository")
class SpringDataApplication {
...
}
您可能更喜欢使用类型安全的 basePackageClasses 属性,而不是使用 basePackages 属性。basePackageClasses 允许您通过仅指定一个应用程序 Repository 接口类型来指定包含所有应用程序 Repository 类的包。考虑在每个包中创建一个特殊的无操作标记类或接口,其唯一目的是标识此属性引用的应用程序 Repositories 的位置。
除了 basePackages 和 basePackageClasses 属性之外,与 Spring 的 @ComponentScan 注解一样,@EnableGemfireRepositories 注解还提供了基于 Spring ComponentScan.Filter 类型的包含和排除过滤器。您可以使用 filterType 属性按不同方面进行过滤,例如应用程序 Repository 类型是否使用特定注解进行注解或是否扩展了特定类类型等。有关更多详细信息,请参阅 FilterType Javadoc。
@EnableGemfireRepositories 注解还允许您使用 namedQueriesLocation 属性指定命名 OQL 查询的位置,这些查询位于 Java Properties 文件中。属性名称必须与 Repository 查询方法的名称匹配,并且属性值是您希望在调用 Repository 查询方法时执行的 OQL 查询。
如果您的应用程序需要一个或多个自定义存储库实现,可以将 repositoryImplementationPostfix 属性设置为备用值(默认为 Impl)。此功能通常用于扩展 Spring Data Repository 基础设施,以实现数据存储(例如 SDG)未提供的功能。
在 Pivotal GemFire 中需要自定义存储库实现的一个例子是执行联接。SDG Repositories 不支持联接。对于 Pivotal GemFire PARTITION 区域,联接必须在共置的 PARTITION 区域上执行,因为 Pivotal GemFire 不支持“分布式”联接。此外,等值联接 OQL 查询必须在 Pivotal GemFire 函数内部执行。有关 Pivotal GemFire 等值联接查询的更多详细信息,请参阅此处。
SDG Repository 基础设施扩展的许多其他方面也可以进行定制。有关所有配置设置的更多详细信息,请参阅 @EnableGemfireRepositories Javadoc。
10.3. 执行 OQL 查询
Spring Data for Pivotal GemFire Repositories 允许定义查询方法,以便轻松地针对托管实体映射的区域执行 Pivotal GemFire OQL 查询,如以下示例所示
@Region("People")
public class Person { … }
public interface PersonRepository extends CrudRepository<Person, Long> {
Person findByEmailAddress(String emailAddress);
Collection<Person> findByFirstname(String firstname);
@Query("SELECT * FROM /People p WHERE p.firstname = $1")
Collection<Person> findByFirstnameAnnotated(String firstname);
@Query("SELECT * FROM /People p WHERE p.firstname IN SET $1")
Collection<Person> findByFirstnamesAnnotated(Collection<String> firstnames);
}
上述示例中列出的第一个查询方法导致派生以下 OQL 查询:SELECT x FROM /People x WHERE x.emailAddress = $1。第二个查询方法的工作方式相同,只是它返回所有找到的实体,而第一个查询方法期望找到单个结果。
如果支持的关键字不足以声明和表达您的 OQL 查询,或者方法名称变得过于冗长,那么您可以像第三和第四个方法所示,使用 @Query 注解查询方法。
下表简要列出了查询方法中可以使用的支持关键字的示例
| 关键字 | 示例 | 逻辑结果 |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
(无关键字) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10.4. 使用注解的 OQL 查询扩展
许多查询语言,例如 Pivotal GemFire 的 OQL (Object Query Language),都有 Spring Data Commons' Repository 基础设施不直接支持的扩展。
Spring Data Commons' Repository 基础设施的目标之一是充当最低公分母,以保持对当今应用程序开发中可用和使用的最广泛数据存储阵列的支持和可移植性。从技术上讲,这意味着开发人员可以通过重用其现有的应用程序特定 Repository 接口来访问其应用程序中 Spring Data Commons 支持的多个不同数据存储——这是一种方便而强大的抽象。
为了支持 Pivotal GemFire 的 OQL 查询语言扩展并保持不同数据存储之间的可移植性,Spring Data for Pivotal GemFire 通过使用 Java 注解添加了对 OQL 查询扩展的支持。这些注解将被其他没有类似查询语言功能的 Spring Data Repository 实现(例如 Spring Data JPA 或 Spring Data Redis)忽略。
例如,许多数据存储很可能不会实现 Pivotal GemFire 的 OQL IMPORT 关键字。将 IMPORT 作为注解(即 @Import)而不是作为查询方法签名(特别是方法名称)的一部分实现,不会在评估查询方法名称以构造另一个适用于数据存储的查询时干扰解析基础设施。
目前,Spring Data for Pivotal GemFire 支持的 Pivotal GemFire OQL 查询语言扩展集包括
| 关键字 | 注解 | 描述 | 参数 |
|---|---|---|---|
|
OQL 查询索引提示 |
|
|
|
限定应用程序特定类型。 |
|
|
|
限制返回的查询结果集。 |
|
|
|
启用 OQL 查询特定调试。 |
不适用 |
举例来说,假设您有一个 Customers 应用程序域类和相应的 Pivotal GemFire 区域,以及一个 CustomerRepository 和一个按姓氏查找 Customers 的查询方法,如下所示
package ...;
import org.springframework.data.annotation.Id;
import org.springframework.data.gemfire.mapping.annotation.Region;
...
@Region("Customers")
public class Customer ... {
@Id
private Long id;
...
}
package ...;
import org.springframework.data.gemfire.repository.GemfireRepository;
...
public interface CustomerRepository extends GemfireRepository<Customer, Long> {
@Trace
@Limit(10)
@Hint("LastNameIdx")
@Import("org.example.app.domain.Customer")
List<Customer> findByLastName(String lastName);
...
}
前面的示例产生以下 OQL 查询
<TRACE> <HINT 'LastNameIdx'> IMPORT org.example.app.domain.Customer; SELECT * FROM /Customers x WHERE x.lastName = $1 LIMIT 10
Spring Data for Pivotal GemFire 的 Repository 扩展在 OQL 注解扩展与 @Query 注解结合使用时,会小心不创建冲突的声明。
再举一个例子,假设您在 CustomerRepository 中定义了一个带有原始 @Query 注解的查询方法,如下所示
public interface CustomerRepository extends GemfireRepository<Customer, Long> {
@Trace
@Limit(10)
@Hint("CustomerIdx")
@Import("org.example.app.domain.Customer")
@Query("<TRACE> <HINT 'ReputationIdx'> SELECT DISTINCT * FROM /Customers c WHERE c.reputation > $1 ORDER BY c.reputation DESC LIMIT 5")
List<Customer> findDistinctCustomersByReputationGreaterThanOrderByReputationDesc(Integer reputation);
}
前面的查询方法产生了以下 OQL 查询
IMPORT org.example.app.domain.Customer; <TRACE> <HINT 'ReputationIdx'> SELECT DISTINCT * FROM /Customers x WHERE x.reputation > $1 ORDER BY c.reputation DESC LIMIT 5
@Limit(10) 注解不会覆盖原始查询中明确定义的 LIMIT。此外,@Hint("CustomerIdx") 注解也不会覆盖原始查询中明确定义的 HINT。最后,@Trace 注解是多余的,没有额外的效果。
|
|
10.5. 查询后处理
由于使用了 Spring Data Repository 抽象,用于定义数据存储特定查询(例如 OQL)的查询方法约定既简单又方便。然而,有时仍然希望检查甚至可能修改从 Repository 查询方法生成的查询。
自 2.0.x 版本起,Spring Data for Pivotal GemFire 包含了 o.s.d.gemfire.repository.query.QueryPostProcessor 函数式接口。该接口的宽松定义如下
package org.springframework.data.gemfire.repository.query;
import org.springframework.core.Ordered;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.QueryMethod;
import ...;
@FunctionalInterface
interface QueryPostProcessor<T extends Repository, QUERY> extends Ordered {
QUERY postProcess(QueryMethod queryMethod, QUERY query, Object... arguments);
}
提供了额外的默认方法,允许您组合 QueryPostProcessor 实例,类似于 java.util.function.Function.andThen(:Function) 和 java.util.function.Function.compose(:Function) 的工作方式。
此外,QueryPostProcessor 接口实现了 org.springframework.core.Ordered 接口,这在 Spring 容器中声明和注册多个 QueryPostProcessors 并用于为一组生成的查询方法查询创建处理管道时非常有用。
最后,QueryPostProcessor 接受对应于类型参数 T 和 QUERY 的类型参数。类型 T 扩展了 Spring Data Commons 标记接口 org.springframework.data.repository.Repository。我们将在本节后面进一步讨论。Spring Data for Pivotal GemFire 中的所有 QUERY 类型参数都是 java.lang.String 类型。
将查询定义为 QUERY 类型很有用,因为此 QueryPostProcessor 接口可能会移植到 Spring Data Commons,因此必须处理不同数据存储(例如 JPA、MongoDB 或 Redis)的所有形式的查询。 |
您可以实现此接口,以便在调用应用程序 Repository 接口方法时,接收包含从该方法生成的查询的回调。
例如,您可能希望记录所有应用程序 Repository 接口定义中的所有查询。您可以使用以下 QueryPostProcessor 实现来完成此操作
package example;
import ...;
class LoggingQueryPostProcessor implements QueryPostProcessor<Repository, String> {
private Logger logger = Logger.getLogger("someLoggerName");
@Override
public String postProcess(QueryMethod queryMethod, String query, Object... arguments) {
String message = String.format("Executing query [%s] with arguments [%s]", query, Arrays.toString(arguments));
this.logger.info(message);
}
}
LoggingQueryPostProcessor 被类型化为 Spring Data org.springframework.data.repository.Repository 标记接口,因此,它会记录所有应用程序 Repository 接口查询方法生成的查询。
您可以将此日志记录的范围限制为仅来自某些类型的应用程序 Repository 接口的查询,例如 CustomerRepository,如下例所示
interface CustomerRepository extends CrudRepository<Customer, Long> {
Customer findByAccountNumber(String accountNumber);
List<Customer> findByLastNameLike(String lastName);
}
然后,您可以将 LoggingQueryPostProcessor 特别类型化为 CustomerRepository,如下所示
class LoggingQueryPostProcessor implements QueryPostProcessor<CustomerRepository, String> { .. }
因此,只记录在 CustomerRepository 接口中定义的查询,例如 findByAccountNumber。
您可能希望为由 Repository 查询方法定义的特定查询创建 QueryPostProcessor。例如,假设您希望将从 CustomerRepository.findByLastNameLike(:String) 查询方法生成的 OQL 查询限制为仅返回五个结果,并按 firstName 升序排序 Customers。为此,您可以定义一个自定义 QueryPostProcessor,如以下示例所示
class OrderedLimitedCustomerByLastNameQueryPostProcessor implements QueryPostProcessor<CustomerRepository, String> {
private final int limit;
public OrderedLimitedCustomerByLastNameQueryPostProcessor(int limit) {
this.limit = limit;
}
@Override
public String postProcess(QueryMethod queryMethod, String query, Object... arguments) {
return "findByLastNameLike".equals(queryMethod.getName())
? query.trim()
.replace("SELECT", "SELECT DISTINCT")
.concat(" ORDER BY firstName ASC")
.concat(String.format(" LIMIT %d", this.limit))
: query;
}
}
虽然前面的示例有效,但您可以使用 Spring Data for Pivotal GemFire 提供的 Spring Data Repository 约定来实现相同的效果。例如,相同的查询可以定义如下
interface CustomerRepository extends CrudRepository<Customer, Long> {
@Limit(5)
List<Customer> findDistinctByLastNameLikeOrderByFirstNameDesc(String lastName);
}
但是,如果您无法控制应用程序 CustomerRepository 接口定义,那么 QueryPostProcessor(即 OrderedLimitedCustomerByLastNameQueryPostProcessor)会很方便。
如果您想确保 LoggingQueryPostProcessor 始终在 Spring ApplicationContext 中可能已声明和注册的其他应用程序定义的 QueryPostProcessors 之后,可以通过覆盖 o.s.core.Ordered.getOrder() 方法来设置 order 属性,如以下示例所示
order 属性class LoggingQueryPostProcessor implements QueryPostProcessor<Repository, String> {
@Override
int getOrder() {
return 1;
}
}
class CustomerQueryPostProcessor implements QueryPostProcessor<CustomerRepository, String> {
@Override
int getOrder() {
return 0;
}
}
这确保您始终在 LoggingQueryPostProcessor 记录查询之前看到其他 QueryPostProcessors 应用的后处理效果。
您可以在 Spring ApplicationContext 中定义任意数量的 QueryPostProcessors,并以任何顺序将它们应用于所有或特定的应用程序 Repository 接口,并且可以使用 postProcess(..) 方法回调提供的参数进行细粒度控制。
11. 函数执行的注解支持
Spring Data for Pivotal GemFire 包含注解支持,以简化与 Pivotal GemFire 函数执行的交互。
在底层,Pivotal GemFire API 提供了类来实现和注册部署在 Pivotal GemFire 服务器上的 Pivotal GemFire 函数,然后其他对等成员应用程序或缓存客户端可以远程调用这些函数。
函数可以并行执行,分布在集群中的多个 Pivotal GemFire 服务器上,使用 Map-Reduce 模式聚合结果并返回给调用者。函数也可以指定在单个服务器或区域上运行。Pivotal GemFire API 支持通过各种预定义范围(在区域上、在成员(组中)、在服务器上等)进行远程函数执行。远程函数的实现和执行,与任何 RPC 协议一样,需要一些样板代码。
Spring Data for Pivotal GemFire,秉承 Spring 的核心价值主张,旨在隐藏远程函数执行的机制,让您专注于核心 POJO 编程和业务逻辑。为此,Spring Data for Pivotal GemFire 引入了注解,以声明性地将 POJO 类的公共方法注册为 Pivotal GemFire 函数,以及使用注解接口调用已注册函数(包括远程调用)的功能。
11.1. 实现与执行
需要解决两个不同的关注点:实现和执行。
首先是函数实现(服务器端),它必须与 FunctionContext 交互,以访问调用参数、ResultsSender 以发送结果以及其他执行上下文信息。函数实现通常访问缓存和区域,并使用唯一的 ID 注册到 FunctionService。
调用函数的缓存客户端应用程序不依赖于实现。为了调用函数,应用程序实例化一个 Execution,提供函数 ID、调用参数和函数目标,后者定义其范围:区域、服务器、多个服务器、成员或多个成员。如果函数产生结果,调用者使用 ResultCollector 来聚合和获取执行结果。在某些情况下,需要自定义 ResultCollector 实现,并可以将其注册到 Execution 中。
“客户端”和“服务器”在这里用于函数执行的上下文,这可能与 Pivotal GemFire 客户端-服务器拓扑中的客户端和服务器具有不同的含义。虽然使用 ClientCache 实例的应用程序通常在集群中的一个或多个 Pivotal GemFire 服务器上调用函数,但也可以在对等(P2P)配置中执行函数,其中应用程序是托管对等 Cache 实例的集群成员。请记住,对等成员缓存应用程序受作为集群对等成员的所有约束。 |
11.2. 实现一个函数
使用 Pivotal GemFire API,FunctionContext 提供了一个运行时调用上下文,其中包括客户端的调用参数和用于将结果发送回客户端的 ResultSender 实现。此外,如果函数在区域上执行,FunctionContext 实际上是 RegionFunctionContext 的实例,它提供额外的信息,例如调用函数的目录区域,与 Execution 关联的任何过滤器(一组特定键)等等。如果区域是 PARTITION 区域,函数应使用 PartitionRegionHelper 提取本地数据集。
通过使用 Spring,您可以编写一个简单的 POJO,并使用 Spring 容器将您的 POJO 的一个或多个公共方法绑定到一个函数。旨在用作函数的 POJO 方法的签名通常必须符合客户端的执行参数。然而,在区域执行的情况下,区域数据也可以提供(大概数据保存在本地分区中,如果区域是 PARTITION 区域)。
此外,该函数可能需要应用的过滤器(如果有)。这表明客户端和服务器共享一个调用参数的契约,但方法签名可能包含额外的参数,用于传递 FunctionContext 提供的值。一种可能性是客户端和服务器共享一个公共接口,但这并非严格要求。唯一的约束是,在解析额外参数(即区域数据和过滤器)后,剩余参数必须在顺序和类型上与预期的函数方法参数完全对应。
例如,假设客户端提供一个 String 和一个 int 作为调用参数。这些在 FunctionContext 中作为数组提供,如以下示例所示
Object[] args = new Object[] { "test", 123 };
Spring 容器应该能够绑定到类似于以下的方法签名(暂时忽略返回类型)
public Object method1(String s1, int i2) { ... }
public Object method2(Map<?, ?> data, String s1, int i2) { ... }
public Object method3(String s1, Map<?, ?> data, int i2) { ... }
public Object method4(String s1, Map<?, ?> data, Set<?> filter, int i2) { ... }
public void method4(String s1, Set<?> filter, int i2, Region<?,?> data) { ... }
public void method5(String s1, ResultSender rs, int i2) { ... }
public void method6(FunctionContest context) { ... }
一般规则是,一旦解决了任何附加参数(即区域数据和过滤器),剩余的参数必须在顺序和类型上与预期的函数方法参数完全对应。方法的返回类型必须是 void 或可序列化的类型(作为 java.io.Serializable、DataSerializable 或 PdxSerializable)。后者也是调用参数的要求。
区域数据通常应定义为 Map,以方便单元测试,但如有必要,也可以是 Region 类型。如前面的示例所示,如果需要控制结果如何返回给客户端,也可以直接传递 FunctionContext 本身或 ResultSender。
11.2.1. 函数实现的注解
以下示例展示了 SDG 的 Function 注解如何用于将 POJO 方法公开为 Pivotal GemFire Functions
@Component
public class ApplicationFunctions {
@GemfireFunction
public String function1(String value, @RegionData Map<?, ?> data, int i2) { ... }
@GemfireFunction(id = "myFunction", batchSize=100, HA=true, optimizedForWrite=true)
public List<String> function2(String value, @RegionData Map<?, ?> data, int i2, @Filter Set<?> keys) { ... }
@GemfireFunction(hasResult=true)
public void functionWithContext(FunctionContext functionContext) { ... }
}
请注意,类本身必须注册为 Spring bean,并且每个 Pivotal GemFire 函数都使用 @GemfireFunction 进行注解。在前面的示例中,使用了 Spring 的 @Component 注解,但您可以使用 Spring 支持的任何方法(例如 XML 配置或使用 Spring Boot 时的 Java 配置类)注册 bean。这允许 Spring 容器创建此类的实例并将其包装在 PojoFunctionWrapper 中。Spring 为每个用 @GemfireFunction 注解的方法创建一个包装器实例。每个包装器实例共享相同的目标对象实例以调用相应的方法。
POJO 函数类是 Spring bean 的事实可能带来其他好处。因为它与 Pivotal GemFire 组件(例如缓存和区域)共享 ApplicationContext,所以在必要时可以将这些组件注入到类中。 |
Spring 创建包装器类并将函数注册到 Pivotal GemFire 的 FunctionService。用于注册每个函数的函数 ID 必须是唯一的。根据约定,它默认为简单(不合格)的方法名称。名称可以通过 @GemfireFunction 注解的 id 属性显式定义。
@GemfireFunction 注解还提供了其他配置属性:HA 和 optimizedForWrite,它们对应于 Pivotal GemFire 的 Function 接口定义的属性。
如果 POJO 函数方法的返回类型为 void,则 hasResult 属性会自动设置为 false。否则,如果方法返回一个值,hasResult 属性会设置为 true。即使对于 void 方法返回类型,GemfireFunction 注解的 hasResult 属性也可以设置为 true 来覆盖此约定,如前面所示的 functionWithContext 方法。据推测,其意图是您将直接使用 ResultSender 将结果发送给调用者。
最后,GemfireFunction 注解支持 requiredPermissions 属性,该属性指定执行 Function 所需的权限。默认情况下,所有 Function 都需要 DATA:WRITE 权限。该属性接受一个字符串数组,允许您根据应用程序和/或 Function UC 的需要修改权限。每个资源权限的预期格式为:<RESOURCE>:<OPERATION>:[Target]:[Key]。
RESOURCE 可以是 {data-store-javadoc]/org/apache/geode/security/ResourcePermission.Resource.html[ResourcePermission.Resource] 枚举值中的一个。OPERATION 可以是 {data-store-javadoc}/org/apache/geode/security/ResourcePermission.Operation.html[ResourcePermission.Operation] 枚举值中的一个。可选地,Target 可以是 Region 的名称或 {data-store-javadoc}/org/apache/geode/security/ResourcePermission.Target.html[ResourcePermission.Target] 枚举值中的一个。最后,可选地,如果指定了 Target Region,Key 是 Target Region 中的一个有效 Key。
PojoFunctionWrapper 实现了 Pivotal GemFire 的 Function 接口,绑定方法参数,并在其 execute() 方法中调用目标方法。它还使用 ResultSender 将方法的返回值发送回调用者。
11.2.2. 批量处理结果
如果返回类型是数组或 Collection,则必须考虑如何返回结果。默认情况下,PojoFunctionWrapper 一次性返回整个数组或 Collection。如果数组或 Collection 中的元素数量非常大,可能会导致性能损失。要将有效负载分成更小、更易于管理的数据块,您可以设置 batchSize 属性,如前面所示的 function2 中所示。
如果您需要对 ResultSender 进行更多控制,特别是如果方法本身会使用太多内存来创建 Collection,您可以传入 ResultSender 或通过 FunctionContext 访问它,并直接在方法中使用它将结果发送回调用者。 |
11.2.3. 启用注解处理
根据 Spring 标准,您必须明确激活 @GemfireFunction 注解的注解处理。以下示例通过 XML 激活注解处理
<gfe:annotation-driven/>
以下示例通过注解 Java 配置类来激活注解处理
@Configuration
@EnableGemfireFunctions
class ApplicationConfiguration { ... }
11.3. 执行函数
调用远程函数的进程需要提供函数的 ID、调用参数、执行目标(onRegion、onServers、onServer、onMember 或 onMembers)以及(可选)过滤器集。通过使用 Spring Data for Pivotal GemFire,您所需要做的就是定义一个由注解支持的接口。Spring 为该接口创建一个动态代理,该代理使用 FunctionService 来创建 Execution、调用 Execution,并(如有必要)将结果强制转换为定义的返回类型。此技术类似于 Spring Data for Pivotal GemFire 的 Repository 扩展的工作方式。因此,一些配置和概念应该很熟悉。
通常,单个接口定义映射到多个函数执行,每个函数执行对应于接口中定义的每个方法。
11.3.1. 函数执行的注解
为了支持客户端函数执行,提供了以下 SDG Function 注解:@OnRegion、@OnServer、@OnServers、@OnMember 和 @OnMembers。这些注解对应于 Pivotal GemFire 的 FunctionService 类提供的 Execution 实现。
每个注解都公开了适当的属性。这些注解还提供了一个可选的 resultCollector 属性,其值是实现 ResultCollector 接口的 Spring bean 的名称,用于执行。
| 代理接口将所有声明的方法绑定到相同的执行配置。尽管预计单个方法接口很常见,但接口中的所有方法都由相同的代理实例支持,因此都共享相同的配置。 |
以下清单显示了一些示例
@OnRegion(region="SomeRegion", resultCollector="myCollector")
public interface FunctionExecution {
@FunctionId("function1")
String doIt(String s1, int i2);
String getString(Object arg1, @Filter Set<Object> keys);
}
默认情况下,Function ID 是简单的(非限定)方法名。@FunctionId 注解可用于将此调用绑定到不同的 Function ID。
11.3.2. 启用注解处理
客户端使用 Spring 的 classpath 组件扫描功能来发现带注解的接口。要在 XML 中启用 Function 执行注解处理,请在 XML 配置中插入以下元素
<gfe-data:function-executions base-package="org.example.myapp.gemfire.functions"/>
function-executions 元素在 gfe-data XML 命名空间中提供。base-package 属性是必需的,以避免扫描整个 classpath。可以提供额外的过滤器,如 Spring 参考文档中所述。
或者,您可以按如下方式注解您的 Java 配置类
@EnableGemfireFunctionExecutions(basePackages = "org.example.myapp.gemfire.functions")
11.4. 程序化函数执行
使用上一节中定义的函数执行注解接口,只需将您的接口自动装配到将调用函数的应用程序 bean 中即可
@Component
public class MyApplication {
@Autowired
FunctionExecution functionExecution;
public void doSomething() {
functionExecution.doIt("hello", 123);
}
}
或者,您可以直接使用函数执行模板。在以下示例中,GemfireOnRegionFunctionTemplate 创建了一个 onRegion 函数 Execution
GemfireOnRegionFunctionTemplateSet<?, ?> myFilter = getFilter();
Region<?, ?> myRegion = getRegion();
GemfireOnRegionOperations template = new GemfireOnRegionFunctionTemplate(myRegion);
String result = template.executeAndExtract("someFunction", myFilter, "hello", "world", 1234);
在内部,函数 Executions 总是返回一个 List。executeAndExtract 假设一个包含结果的单例 List,并尝试将该值强制转换为请求的类型。还有一个 execute 方法返回原样的 List。第一个参数是函数 ID。过滤器参数是可选的。其余参数是可变参数 List。
11.5. 使用 PDX 进行函数执行
当使用 Spring Data for Pivotal GemFire 的 Function 注解支持结合 Pivotal GemFire 的 PDX 序列化时,有几个后勤问题需要注意。
如本节前面所解释的,通过示例,您通常应该使用带有 Spring Data for Pivotal GemFire Function 注解的 POJO 类来定义 Pivotal GemFire Functions,如下所示
public class OrderFunctions {
@GemfireFunction(...)
Order process(@RegionData data, Order order, OrderSource orderSourceEnum, Integer count) { ... }
}
Integer 类型的 count 参数是任意的,Order 类和 OrderSource 枚举的分离也是任意的,它们结合起来可能更符合逻辑。然而,这些参数以这种方式设置是为了演示在 PDX 上下文中的 Function 执行问题。 |
您的 Order 类和 OrderSource 枚举可能定义如下
public class Order ... {
private Long orderNumber;
private LocalDateTime orderDateTime;
private Customer customer;
private List<Item> items
...
}
public enum OrderSource {
ONLINE,
PHONE,
POINT_OF_SALE
...
}
当然,您可以定义一个 Function Execution 接口来调用 'process' Pivotal GemFire 服务器 Function,如下所示
@OnServer
public interface OrderProcessingFunctions {
Order process(Order order, OrderSource orderSourceEnum, Integer count);
}
显然,这个 process(..) Order 函数是从客户端通过 ClientCache 实例(即 <gfe:client-cache/>)调用的。这意味着函数参数也必须是可序列化的。当在集群中的 peer 之间调用 peer-to-peer 成员函数(例如 @OnMember(s))时,也是如此。任何形式的 distribution 都要求客户端和服务器(或 peers)之间传输的数据是序列化的。
现在,如果您已将 Pivotal GemFire 配置为使用 PDX 进行序列化(例如,而不是 Java 序列化),您还可以在 Pivotal GemFire 服务器的配置中将 pdx-read-serialized 属性设置为 true,如下所示
<gfe:cache ... pdx-read-serialized="true"/>
或者,您可以为 Pivotal GemFire 缓存客户端应用程序将 pdx-read-serialized 属性设置为 true,如下所示
<gfe:client-cache ... pdx-read-serialized="true"/>
这样做会导致从缓存(即 Region)读取的所有值以及客户端和服务器(或 peers)之间传递的信息都保持序列化形式,包括但不限于函数参数。
Pivotal GemFire 仅序列化您已通过 Pivotal GemFire 的 ReflectionBasedAutoSerializer 明确配置(注册)或(推荐)使用“自定义” Pivotal GemFire PdxSerializer 的应用程序域对象类型。如果您使用 Spring Data for Pivotal GemFire 的 Repository 扩展,您甚至可能希望考虑使用 Spring Data for Pivotal GemFire 的 MappingPdxSerializer,它使用实体的映射元数据来确定从应用程序域对象序列化到 PDX 实例的数据。
然而,不那么明显的是,无论 Java Enum 类型是否明确配置(即,使用正则表达式模式和 classes 参数注册到 ReflectionBasedAutoSerializer,或者由“自定义” Pivotal GemFire PdxSerializer 处理),Pivotal GemFire 都会自动处理它们,尽管 Java 枚举实现了 java.io.Serializable。
因此,当您在注册了 Pivotal GemFire Function(包括 Spring Data for Pivotal GemFire Function-annotated POJO 类)的 Pivotal GemFire 服务器上将 pdx-read-serialized 设置为 true 时,您在调用 Function Execution 时可能会遇到令人惊讶的行为。
您在调用函数时可能会传递以下参数
orderProcessingFunctions.process(new Order(123, customer, LocalDateTime.now(), items), OrderSource.ONLINE, 400);
但是,服务器上的 Pivotal GemFire Function 获得以下内容
process(regionData, order:PdxInstance, :PdxInstanceEnum, 400);
Order 和 OrderSource 已作为 PDX 实例传递给函数。再次强调,这一切都是因为 pdx-read-serialized 设置为 true,这在 Pivotal GemFire 服务器与多个不同的客户端(例如,Java 客户端和原生客户端(如 C/C++、C# 等)的组合)交互的情况下可能是必要的。
这与 Spring Data for Pivotal GemFire 强类型 Function 注解的 POJO 类方法签名相悖,在这些签名中,您通常会合理地期望应用程序域对象类型,而不是 PDX 序列化实例。
因此,Spring Data for Pivotal GemFire 包含了增强的 Function 支持,可以自动将 PDX 类型的方法参数转换为 Function 方法签名(参数类型)定义的所需应用程序域对象类型。
然而,这也要求您在注册和使用 Spring Data for Pivotal GemFire Function 注解的 POJO 的 Pivotal GemFire 服务器上明确注册一个 Pivotal GemFire PdxSerializer,如以下示例所示
<bean id="customPdxSerializer" class="x.y.z.gemfire.serialization.pdx.MyCustomPdxSerializer"/>
<gfe:cache ... pdx-serializer-ref="customPdxSerializeer" pdx-read-serialized="true"/>
或者,为了方便起见,您可以使用 Pivotal GemFire 的 ReflectionBasedAutoSerializer。当然,我们建议在可能的情况下使用自定义 PdxSerializer 来更好地控制您的序列化策略。
最后,Spring Data for Pivotal GemFire 小心翼翼地不转换您的函数参数,如果您将您的函数参数视为通用类型或 Pivotal GemFire 的 PDX 类型之一,如下所示
@GemfireFunction
public Object genericFunction(String value, Object domainObject, PdxInstanceEnum enum) {
...
}
仅当相应的应用程序域类型在 classpath 上且 Function 注解的 POJO 方法期望它时,Spring Data for Pivotal GemFire 才会将 PDX 类型数据转换为相应的应用程序域类型。
有关自定义、复合应用程序特定 Pivotal GemFire PdxSerializers 以及基于方法签名适当的 POJO Function 参数类型处理的良好示例,请参阅 Spring Data for Pivotal GemFire 的 ClientCacheFunctionExecutionWithPdxIntegrationTest 类。
12. Apache Lucene 集成
Pivotal GemFire 与 Apache Lucene 集成,让您可以使用 Lucene 查询索引和搜索存储在 Pivotal GemFire 中的数据。基于搜索的查询还包括分页查询结果的能力。
此外,Spring Data for Pivotal GemFire 增加了对基于 Spring Data Commons 投影基础设施的查询投影的支持。此功能允许根据应用程序的需要将查询结果投影到一流的应用程序域类型中。
在运行任何基于 Lucene 搜索的查询之前,必须创建 Lucene Index。LuceneIndex 可以在 Spring (Data for Pivotal GemFire) XML 配置中创建,如下所示
<gfe:lucene-index id="IndexOne" fields="fieldOne, fieldTwo" region-path="/Example"/>
此外,Apache Lucene 允许为每个字段指定 分析器,并可以按以下示例进行配置
<gfe:lucene-index id="IndexTwo" lucene-service-ref="luceneService" region-path="/AnotherExample">
<gfe:field-analyzers>
<map>
<entry key="fieldOne">
<bean class="example.AnalyzerOne"/>
</entry>
<entry key="fieldTwo">
<bean class="example.AnalyzerTwo"/>
</entry>
</map>
</gfe:field-analyzers>
</gfe:lucene-index>
Map 可以指定为顶级 bean 定义,并通过嵌套的 <gfe:field-analyzers> 元素中的 ref 属性引用,如下所示:<gfe-field-analyzers ref="refToTopLevelMapBeanDefinition"/>。
Spring Data for Pivotal GemFire 的 LuceneIndexFactoryBean API 和 SDG 的 XML 命名空间还允许在创建 LuceneIndex 时指定 org.apache.geode.cache.lucene.LuceneSerializer。LuceneSerializer 允许您配置对象在索引时如何转换为 Lucene 文档。
以下示例显示了如何将 LuceneSerializer 添加到 LuceneIndex
<bean id="MyLuceneSerializer" class="example.CustomLuceneSerializer"/>
<gfe:lucene-index id="IndexThree" lucene-service-ref="luceneService" region-path="/YetAnotherExample">
<gfe:lucene-serializer ref="MyLuceneSerializer">
</gfe:lucene-index>
您也可以将 LuceneSerializer 指定为匿名嵌套 bean 定义,如下所示
<gfe:lucene-index id="IndexThree" lucene-service-ref="luceneService" region-path="/YetAnotherExample">
<gfe:lucene-serializer>
<bean class="example.CustomLuceneSerializer"/>
</gfe:lucene-serializer>
</gfe:lucene-index>
或者,您可以在 Spring Java 配置中,在 @Configuration 类中声明或定义 LuceneIndex,如以下示例所示
@Bean(name = "Books")
@DependsOn("bookTitleIndex")
PartitionedRegionFactoryBean<Long, Book> booksRegion(GemFireCache gemfireCache) {
PartitionedRegionFactoryBean<Long, Book> peopleRegion =
new PartitionedRegionFactoryBean<>();
peopleRegion.setCache(gemfireCache);
peopleRegion.setClose(false);
peopleRegion.setPersistent(false);
return peopleRegion;
}
@Bean
LuceneIndexFactoryBean bookTitleIndex(GemFireCache gemFireCache,
LuceneSerializer luceneSerializer) {
LuceneIndexFactoryBean luceneIndex = new LuceneIndexFactoryBean();
luceneIndex.setCache(gemFireCache);
luceneIndex.setFields("title");
luceneIndex.setLuceneSerializer(luceneSerializer);
luceneIndex.setRegionPath("/Books");
return luceneIndex;
}
@Bean
CustomLuceneSerializer myLuceneSerialier() {
return new CustomeLuceneSerializer();
}
Pivotal GemFire 的 Apache Lucene 集成和支持有一些限制。
首先,LuceneIndex 只能在 Pivotal GemFire PARTITION Region 上创建。
其次,所有 LuceneIndexes 必须在 LuceneIndex 所应用的 Region 之前创建。
为了确保在 Spring 容器中定义的所有声明的 LuceneIndexes 在其所应用的 Region 之前创建,SDG 包含了 org.springframework.data.gemfire.config.support.LuceneIndexRegionBeanFactoryPostProcessor。您可以通过使用 <bean class="org.springframework.data.gemfire.config.support.LuceneIndexRegionBeanFactoryPostProcessor"/> 在 XML 配置中注册此 Spring BeanFactoryPostProcessor。o.s.d.g.config.support.LuceneIndexRegionBeanFactoryPostProcessor 只能在使用 SDG XML 配置时使用。有关 Spring 的 BeanFactoryPostProcessors 的更多详细信息,请参见 此处。 |
Pivotal GemFire 的这些限制在未来的版本中可能不适用,这就是为什么 SDG LuceneIndexFactoryBean API 也直接引用了 Region,而不仅仅是 Region 路径。
当您希望在应用程序生命周期后期以及需求要求时,在具有数据的现有 Region 上定义 LuceneIndex 时,这更理想。在可能的情况下,SDG 努力遵守强类型对象。但是,目前您必须使用 regionPath 属性来指定应用 LuceneIndex 的 Region。
此外,在前面的示例中,请注意 Books Region bean 定义上存在 Spring 的 @DependsOn 注解。这会从 Books Region bean 创建到 bookTitleIndex LuceneIndex bean 定义的依赖关系,确保在应用 LuceneIndex 的 Region 之前创建 LuceneIndex。 |
现在,一旦我们有了 LuceneIndex,我们就可以执行基于 Lucene 的数据访问操作,例如查询。
12.1. Lucene 模板数据访问器
Spring Data for Pivotal GemFire 提供了两个用于 Lucene 数据访问操作的主要模板,具体取决于您的应用程序准备处理的级别。
LuceneOperations 接口使用 Pivotal GemFire Lucene 类型定义查询操作,这些类型在以下接口定义中定义
public interface LuceneOperations {
<K, V> List<LuceneResultStruct<K, V>> query(String query, String defaultField [, int resultLimit]
, String... projectionFields);
<K, V> PageableLuceneQueryResults<K, V> query(String query, String defaultField,
int resultLimit, int pageSize, String... projectionFields);
<K, V> List<LuceneResultStruct<K, V>> query(LuceneQueryProvider queryProvider [, int resultLimit]
, String... projectionFields);
<K, V> PageableLuceneQueryResults<K, V> query(LuceneQueryProvider queryProvider,
int resultLimit, int pageSize, String... projectionFields);
<K> Collection<K> queryForKeys(String query, String defaultField [, int resultLimit]);
<K> Collection<K> queryForKeys(LuceneQueryProvider queryProvider [, int resultLimit]);
<V> Collection<V> queryForValues(String query, String defaultField [, int resultLimit]);
<V> Collection<V> queryForValues(LuceneQueryProvider queryProvider [, int resultLimit]);
}
[, int resultLimit] 表示 resultLimit 参数是可选的。 |
LuceneOperations 接口中的操作与 Pivotal GemFire 的 LuceneQuery 接口提供的操作相匹配。然而,SDG 具有将专有 Pivotal GemFire 或 Apache Lucene Exceptions 转换为 Spring 的高度一致和富有表现力的 DAO 异常层次结构的附加价值,尤其是在许多现代数据访问操作涉及多个存储或存储库时。
此外,SDG 的 LuceneOperations 接口可以在底层 Pivotal GemFire 或 Apache Lucene API 发生接口破坏性更改时保护您的应用程序。
然而,如果仅使用 Pivotal GemFire 和 Apache Lucene 数据类型(如 Pivotal GemFire 的 LuceneResultStruct)提供 Lucene 数据访问对象 (DAO),那将是令人遗憾的。因此,SDG 为您提供了 ProjectingLuceneOperations 接口来解决这些重要的应用程序问题。以下清单显示了 ProjectingLuceneOperations 接口定义
public interface ProjectingLuceneOperations {
<T> List<T> query(String query, String defaultField [, int resultLimit], Class<T> projectionType);
<T> Page<T> query(String query, String defaultField, int resultLimit, int pageSize, Class<T> projectionType);
<T> List<T> query(LuceneQueryProvider queryProvider [, int resultLimit], Class<T> projectionType);
<T> Page<T> query(LuceneQueryProvider queryProvider, int resultLimit, int pageSize, Class<T> projectionType);
}
ProjectingLuceneOperations 接口主要使用应用程序域对象类型,让您可以使用应用程序数据。query 方法变体接受投影类型,模板使用 Spring Data Commons 投影基础设施将查询结果应用于给定投影类型的实例。
此外,该模板将分页的 Lucene 查询结果包装在 Spring Data Commons Page 抽象的实例中。相同的投影逻辑仍然可以应用于页面中的结果,并在访问集合中的每个页面时进行延迟投影。
举例来说,假设您有一个表示 Person 的类,如下所示
class Person {
Gender gender;
LocalDate birthDate;
String firstName;
String lastName;
...
String getName() {
return String.format("%1$s %2$s", getFirstName(), getLastName());
}
}
此外,您可能有一个单一接口来表示人员为 Customers,具体取决于您的应用程序视图,如下所示
interface Customer {
String getName()
}
如果我定义以下 LuceneIndex…
@Bean
LuceneIndexFactoryBean personLastNameIndex(GemFireCache gemfireCache) {
LuceneIndexFactoryBean personLastNameIndex =
new LuceneIndexFactoryBean();
personLastNameIndex.setCache(gemfireCache);
personLastNameIndex.setFields("lastName");
personLastNameIndex.setRegionPath("/People");
return personLastNameIndex;
}
那么您可以查询作为 Person 对象的个人,如下所示
List<Person> people = luceneTemplate.query("lastName: D*", "lastName", Person.class);
或者,您可以查询 Customer 类型的 Page,如下所示
Page<Customer> customers = luceneTemplate.query("lastName: D*", "lastName", 100, 20, Customer.class);
然后可以使用 Page 来获取结果的单个页面,如下所示
List<Customer> firstPage = customers.getContent();
方便的是,Spring Data Commons Page 接口也实现了 java.lang.Iterable<T>,使得遍历其内容变得容易。
Spring Data Commons Projection 基础设施的唯一限制是投影类型必须是一个接口。但是,可以扩展提供的 SDC Projection 基础设施并提供一个自定义的 ProjectionFactory,它使用 CGLIB 来生成作为投影实体的代理类。
您可以使用 setProjectionFactory(:ProjectionFactory) 在 Lucene 模板上设置自定义 ProjectionFactory。
12.2. 注解配置支持
最后,Spring Data for Pivotal GemFire 为 LuceneIndexes 提供了注解配置支持。
最终,SDG Lucene 支持将进入 Pivotal GemFire 的 Repository 基础设施扩展,以便 Lucene 查询可以像 OQL 支持今天的工作方式一样,在应用程序 Repository 接口上表示为方法。
但是,在此期间,如果您想方便地表达 LuceneIndexes,您可以直接在您的应用程序域对象上进行,如以下示例所示
@PartitionRegion("People")
class Person {
Gender gender;
@Index
LocalDate birthDate;
String firstName;
@LuceneIndex;
String lastName;
...
}
要启用此功能,您必须专门使用 SDG 的注解配置支持,并使用 @EnableEntityDefineRegions 和 @EnableIndexing 注解,如下所示
@PeerCacheApplication
@EnableEntityDefinedRegions
@EnableIndexing
class ApplicationConfiguration {
...
}
LuceneIndexes 只能在 Pivotal GemFire 服务器上创建,因为 LuceneIndexes 仅适用于 PARTITION Regions。 |
鉴于我们前面定义的 Person 类,SDG 注解配置支持会找到 Person 实体类定义,并确定人员存储在一个名为“People”的 PARTITION Region 中,并且 Person 在 birthDate 上有一个 OQL Index,以及在 lastName 上有一个 LuceneIndex。
13. 在 Pivotal GemFire 中引导 Spring ApplicationContext
通常,基于 Spring 的应用程序使用 Spring Data for Pivotal GemFire 的功能引导 Pivotal GemFire。通过指定使用 Spring Data for Pivotal GemFire XML 命名空间的 <gfe:cache/> 元素,将在与您的应用程序相同的 JVM 进程中创建并初始化一个具有默认设置的单个嵌入式 Pivotal GemFire peer Cache 实例。
但是,有时有必要(也许是您的 IT 组织强制要求)Pivotal GemFire 由提供的 Pivotal GemFire 工具套件完全管理和操作,可能使用 Gfsh。通过使用 Gfsh,Pivotal GemFire 引导您的 Spring ApplicationContext,而不是反过来。Pivotal GemFire 负责引导并托管您的应用程序,而不是应用程序服务器或使用 Spring Boot 的 Java main 类。
| Pivotal GemFire 不是应用程序服务器。此外,在使用这种方法时,Pivotal GemFire 缓存配置方面存在限制。 |
13.1. 使用 Pivotal GemFire 引导通过 Gfsh 启动的 Spring Context
要在使用 Gfsh 启动 Pivotal GemFire 服务器时,在 Pivotal GemFire 中引导 Spring ApplicationContext,您必须使用 Pivotal GemFire 的 初始化器功能。初始化器块可以声明一个应用程序回调,该回调在缓存由 Pivotal GemFire 初始化后启动。
初始化器在 initializer 元素中声明,使用 Pivotal GemFire 本机 cache.xml 的最小代码片段。为了引导 Spring ApplicationContext,需要一个 cache.xml 文件,这与引导配置了组件扫描的 Spring ApplicationContext 所需的 Spring XML 配置的最小代码片段(例如 <context:component-scan base-packages="…"/>)非常相似。
幸运的是,框架已经方便地提供了一个这样的初始化器:SpringContextBootstrappingInitializer。
以下示例显示了此类的典型但最小的配置,位于 Pivotal GemFire 的 cache.xml 文件中
<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="http://geode.apache.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://geode.apache.org/schema/cache https://geode.apache.org/schema/cache/cache-1.0.xsd"
version="1.0">
<initializer>
<class-name>org.springframework.data.gemfire.support.SpringContextBootstrappingInitializer</class-name>
<parameter name="contextConfigLocations">
<string>classpath:application-context.xml</string>
</parameter>
</initializer>
</cache>
SpringContextBootstrappingInitializer 类遵循与 Spring 的 ContextLoaderListener 类类似的约定,ContextLoaderListener 类用于在 Web 应用程序中引导 Spring ApplicationContext,其中 ApplicationContext 配置文件由 contextConfigLocations Servlet 上下文参数指定。
此外,SpringContextBootstrappingInitializer 类还可以与 basePackages 参数一起使用,以指定包含适当注解的应用程序组件的逗号分隔基本包列表。Spring 容器会搜索这些组件以在 classpath 中查找和创建 Spring bean 和其他应用程序组件,如以下示例所示
<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="http://geode.apache.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://geode.apache.org/schema/cache https://geode.apache.org/schema/cache/cache-1.0.xsd"
version="1.0">
<initializer>
<class-name>org.springframework.data.gemfire.support.SpringContextBootstrappingInitializer</class-name>
<parameter name="basePackages">
<string>org.mycompany.myapp.services,org.mycompany.myapp.dao,...</string>
</parameter>
</initializer>
</cache>
然后,使用正确配置和构建的 CLASSPATH 和 cache.xml 文件(如前所示),在 Gfsh 中启动 Pivotal GemFire 服务器时,将其指定为命令行选项,命令行如下
gfsh>start server --name=ExampleServer --log-level=config ...
--classpath="/path/to/application/classes.jar:/path/to/spring-data-geode-<major>.<minor>.<maint>.RELEASE.jar"
--cache-xml-file="/path/to/geode/cache.xml"
application-context.xml 可以是任何有效的 Spring 配置元数据,包括所有 SDG XML 命名空间元素。这种方法的唯一限制是 Pivotal GemFire 缓存不能使用 SDG XML 命名空间进行配置。换句话说,<gfe:cache/> 元素的所有属性(例如 cache-xml-location、properties-ref、critical-heap-percentage、pdx-serializer-ref、lock-lease 等)都不能指定。如果使用,这些属性将被忽略。
原因是 Pivotal GemFire 本身在初始化器被调用之前就已经创建并初始化了缓存。结果,缓存已经存在,并且由于它是一个“单例”,它不能被重新初始化或对其任何配置进行增强。
13.2. 懒加载 Pivotal GemFire 组件
Spring Data for Pivotal GemFire 已经支持自动装配 Pivotal GemFire 组件(例如 CacheListeners、CacheLoaders、CacheWriters 等),这些组件通过 SDG 的 WiringDeclarableSupport 类在 cache.xml 中声明和创建,如 使用自动装配和注解进行配置 中所述。但是,这仅在 Spring 进行引导时(即当 Spring 引导 Pivotal GemFire 时)才有效。
当您的 Spring ApplicationContext 由 Pivotal GemFire 引导时,这些 Pivotal GemFire 应用程序组件会被忽略,因为 Spring ApplicationContext 尚未存在。直到 Pivotal GemFire 调用初始化器块时才会创建 Spring ApplicationContext,而这只有在所有其他 Pivotal GemFire 组件(缓存、Region 等)已经创建和初始化之后才会发生。
为了解决这个问题,引入了一个新的 LazyWiringDeclarableSupport 类。这个新类感知 Spring ApplicationContext。这个抽象基类的目的是让任何实现类注册自己,以便在初始化器被调用后,由 Pivotal GemFire 最终创建的 Spring 容器进行配置。本质上,这让您的 Pivotal GemFire 应用程序组件有机会通过 Spring 容器中定义的 Spring bean 进行配置和自动装配。
为了让您的 Pivotal GemFire 应用程序组件由 Spring 容器自动装配,您应该创建一个扩展 LazyWiringDeclarableSupport 的应用程序类,并注解任何需要作为 Spring bean 依赖项提供的类成员,类似于以下示例
public class UserDataSourceCacheLoader extends LazyWiringDeclarableSupport
implements CacheLoader<String, User> {
@Autowired
private DataSource userDataSource;
...
}
正如上面 CacheLoader 示例中暗示的,您可能(尽管很少)在 Pivotal GemFire cache.xml 中定义了 Region 和 CacheListener 组件。CacheLoader 可能需要访问应用程序存储库(或者在 Spring ApplicationContext 中定义的 JDBC DataSource),以便在启动时将 Users 加载到 Pivotal GemFire REPLICATE Region 中。
注意
以这种方式混合 Pivotal GemFire 和 Spring 容器的不同生命周期时要小心。并非所有用例和场景都受支持。Pivotal GemFire cache.xml 配置将类似于以下内容(来自 SDG 的测试套件)
<?xml version="1.0" encoding="UTF-8"?>
<cache xmlns="http://geode.apache.org/schema/cache"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://geode.apache.org/schema/cache https://geode.apache.org/schema/cache/cache-1.0.xsd"
version="1.0">
<region name="Users" refid="REPLICATE">
<region-attributes initial-capacity="101" load-factor="0.85">
<key-constraint>java.lang.String</key-constraint>
<value-constraint>org.springframework.data.gemfire.repository.sample.User</value-constraint>
<cache-loader>
<class-name>
org.springframework.data.gemfire.support.SpringContextBootstrappingInitializerIntegrationTest$UserDataStoreCacheLoader
</class-name>
</cache-loader>
</region-attributes>
</region>
<initializer>
<class-name>org.springframework.data.gemfire.support.SpringContextBootstrappingInitializer</class-name>
<parameter name="basePackages">
<string>org.springframework.data.gemfire.support.sample</string>
</parameter>
</initializer>
</cache>
14. 示例应用程序
| 示例应用程序现在维护在 Spring Pivotal GemFire 示例存储库中。 |
Spring Data for Pivotal GemFire 项目还包含一个示例应用程序。该示例应用程序名为“Hello World”,演示了如何在 Spring 应用程序中配置和使用 Pivotal GemFire。在运行时,该示例提供了一个 shell,让您可以针对数据网格运行各种命令。它为不熟悉基本组件或 Spring 和 Pivotal GemFire 概念的开发人员提供了一个极好的起点。
该示例与发行版捆绑在一起,并且基于 Maven。您可以将其导入任何支持 Maven 的 IDE(例如 Spring Tool Suite),或从命令行运行它们。
14.1. Hello World
“Hello World”示例应用程序演示了 Spring Data for Pivotal GemFire 项目的核心功能。它引导 Pivotal GemFire,配置它,针对缓存执行任意命令,并在应用程序退出时将其关闭。可以同时启动多个应用程序实例并协同工作,无需任何用户干预即可共享数据。
|
在 Linux 下运行 如果您在启动 Pivotal GemFire 或示例时遇到网络问题,请尝试将以下系统属性 java.net.preferIPv4Stack=true 添加到命令行(例如,-Djava.net.preferIPv4Stack=true)。有关替代(全局)修复(尤其是在 Ubuntu 上),请参阅 SGF-28。 |
14.1.1. 启动和停止示例
“Hello World”示例应用程序被设计为独立的 Java 应用程序。它具有一个 main 类,可以从您的 IDE(在 Eclipse 或 STS 中,通过 Run As/Java Application)或通过 Maven 从命令行使用 mvn exec:java 启动。如果 classpath 设置正确,您也可以直接在生成的 artifact 上使用 java。
要停止示例,请在命令行中键入 exit 或按 Ctrl+C 以停止 JVM 并关闭 Spring 容器。
14.1.2. 使用示例
启动后,示例会创建一个共享数据网格,并允许您对其发布命令。输出应类似于以下内容
INFO: Created {data-store-name} Cache [Spring {data-store-name} World] v. X.Y.Z
INFO: Created new cache region [myWorld]
INFO: Member xxxxxx:50694/51611 connecting to region [myWorld]
Hello World!
Want to interact with the world ? ...
Supported commands are:
get <key> - retrieves an entry (by key) from the grid
put <key> <value> - puts a new entry into the grid
remove <key> - removes an entry (by key) from the grid
...
例如,要向网格添加新项目,您可以使用以下命令
-> Bold Section qName:emphasis level:5, chunks:[put 1 unu] attrs:[role:bold]
INFO: Added [1=unu] to the cache
null
-> Bold Section qName:emphasis level:5, chunks:[put 1 one] attrs:[role:bold]
INFO: Updated [1] from [unu] to [one]
unu
-> Bold Section qName:emphasis level:5, chunks:[size] attrs:[role:bold]
1
-> Bold Section qName:emphasis level:5, chunks:[put 2 two] attrs:[role:bold]
INFO: Added [2=two] to the cache
null
-> Bold Section qName:emphasis level:5, chunks:[size] attrs:[role:bold]
2
可以同时运行多个实例。一旦启动,新的 VM 会自动看到现有的区域及其信息,如以下示例所示
INFO: Connected to Distributed System ['Spring {data-store-name} World'=xxxx:56218/49320@yyyyy]
Hello World!
...
-> Bold Section qName:emphasis level:5, chunks:[size] attrs:[role:bold]
2
-> Bold Section qName:emphasis level:5, chunks:[map] attrs:[role:bold]
[2=two] [1=one]
-> Bold Section qName:emphasis level:5, chunks:[query length = 3] attrs:[role:bold]
[one, two]
我们鼓励您尝试该示例,启动(和停止)任意数量的实例,并在一个实例中运行各种命令,然后观察其他实例如何反应。为了保存数据,至少有一个实例必须始终保持活动状态。如果所有实例都关闭,则网格数据将完全销毁。
14.1.3. Hello World 示例说明
“Hello World”示例使用 Spring XML 和注解进行配置。初始引导配置是 app-context.xml,它包含 cache-context.xml 文件中定义的缓存配置,并执行 Spring 组件扫描以查找 Spring 组件。
缓存配置定义了 Pivotal GemFire 缓存、一个区域,以及出于说明目的,一个充当日志记录器的 CacheListener。
主要的 bean 是 HelloWorld 和 CommandProcessor,它们依赖 GemfireTemplate 与分布式结构交互。这两个类都使用注解来定义它们的依赖项和生命周期回调。
资源
附录
附录 A: 命名空间参考
<repositories /> 元素
<repositories /> 元素触发 Spring Data 仓库基础设施的设置。最重要的属性是 base-package,它定义了要扫描 Spring Data 仓库接口的包。参见“[repositories.create-instances.spring]”。下表描述了 <repositories /> 元素的属性
| 名称 | 描述 |
|---|---|
|
定义在自动检测模式下扫描扩展 |
|
定义自动检测自定义仓库实现的后缀。名称以配置的后缀结尾的类被视为候选。默认为 |
|
确定用于创建查找查询的策略。有关详细信息,请参见“[repositories.query-methods.query-lookup-strategies]”。默认为 |
|
定义搜索包含外部定义查询的 Properties 文件的位置。 |
|
是否应考虑嵌套仓库接口定义。默认为 |
附录 B:填充器命名空间参考
<populator /> 元素
<populator /> 元素允许通过 Spring Data 仓库基础设施填充数据存储。[1]
| 名称 | 描述 |
|---|---|
|
从何处查找文件以读取要填充仓库的对象。 |
附录 C:仓库查询关键字
支持的查询关键字
下表列出了 Spring Data 仓库查询派生机制通常支持的关键字。但是,请查阅特定于存储的文档以获取支持关键字的确切列表,因为此处列出的一些关键字可能在特定存储中不受支持。
| 逻辑关键字 | 关键字表达式 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
附录 D:仓库查询返回类型
支持的查询返回类型
下表列出了 Spring Data 仓库通常支持的返回类型。但是,请查阅特定于存储的文档以获取支持返回类型的确切列表,因为此处列出的一些类型可能在特定存储中不受支持。
地理空间类型(例如 GeoResult、GeoResults 和 GeoPage)仅适用于支持地理空间查询的数据存储。 |
| 返回类型 | 描述 |
|---|---|
|
表示无返回值。 |
Primitives |
Java 基本类型。 |
Wrapper types |
Java 包装类型。 |
|
一个唯一的实体。期望查询方法最多返回一个结果。如果未找到结果,则返回 |
|
一个 |
|
一个 |
|
一个 |
|
一个 Java 8 或 Guava |
|
Scala 或 Vavr |
|
一个 Java 8 |
|
|
实现 |
公开构造函数或 |
Vavr |
Vavr 集合类型。有关详细信息,请参见 [repositories.collections-and-iterables.vavr]。 |
|
一个 |
|
一个 Java 8 |
|
一个 |
|
一个带大小的数据块,并指示是否有更多数据可用。需要一个 |
|
一个 |
|
一个结果条目,带有附加信息,例如到参考位置的距离。 |
|
一个 |
|
一个带有 |
|
使用响应式仓库时,Project Reactor |
|
使用响应式仓库时,Project Reactor |
|
使用响应式仓库时,RxJava |
|
使用响应式仓库时,RxJava |
|
使用响应式仓库时,RxJava |