1. 概述

Apache Geode 是一个基于分布式云架构的数据管理解决方案,适用于高性能、低延迟的场景。如果能结合 Spring Data 的编程模型来操作 Geode,开发体验会大幅提升。

本文将带你使用 Spring Data Geode 快速搭建一个连接 Apache Geode 的 Java 客户端应用,涵盖配置、实体映射、Repository 操作、索引、持续查询等核心功能。适合已有 Spring Boot 和缓存使用经验的开发者,避免踩坑,快速上手。

2. Spring Data Geode 简介

Spring Data Geode 是 Spring Data 家族的一员,专为 Apache Geode 设计,提供基于注解和 XML 的配置方式,极大简化了客户端与服务端的集成。

✅ 你可以用它轻松构建:

  • 基于 Spring Boot 的 Geode 缓存客户端
  • 内嵌的 Peer Cache 节点
  • 集成 HTTP 服务、SSL、安全认证等功能

⚠️ 注意:它和 Spring Data GemFire 非常相似,但后者对接的是商业版的 Pivotal GemFire。从技术角度看,Spring Data Geode 是开源社区推荐的首选。

我们接下来会用一系列注解,把一个普通的 Spring Boot 应用“改造”成 Geode 客户端,并实现自动 Region 创建、索引管理、持续查询等能力。

3. Maven 依赖

pom.xml 中引入官方推荐的 Starter:

<dependency>
    <groupId>org.springframework.geode</groupId>
    <artifactId>spring-geode-starter</artifactId>
    <version>1.1.1.RELEASE</version>
</dependency>

这个 Starter 已经包含了 Spring Data Geode 的核心模块、Geode 客户端库以及自动配置支持,开箱即用。

4. 使用 @ClientCacheApplication 构建客户端

首先创建一个标准的 Spring Boot 启动类:

@SpringBootApplication 
public class ClientCacheApp {
    public static void main(String[] args) {
        SpringApplication.run(ClientCacheApp.class, args); 
    } 
}

接着,使用 Spring Data Geode 提供的 @ClientCacheApplication 注解将其升级为 Geode 缓存客户端:

@ClientCacheApplication
@SpringBootApplication 
public class ClientCacheApp {
    public static void main(String[] args) {
        SpringApplication.run(ClientCacheApp.class, args); 
    } 
}

✅ 一句话:@ClientCacheApplication = Spring Boot + Geode 客户端上下文。

⚠️ 注意:此时还不能直接运行,必须先启动 Geode 服务端。

5. 启动 Apache Geode 服务端

假设你已经安装好 Apache Geode 并配置了 gfsh 命令行工具(官方推荐方式),接下来启动一个最基本的集群环境。

启动 Locator(协调节点)

gfsh> start locator --name="basicLocator"

启动 Server(数据节点)

gfsh> start server --name="basicServer"

查看集群成员

gfsh> list members

正常输出如下:

    Name     | Id
------------ | ------------------------------------------------------------------
basicLocator | 10.25.3.192(basicLocator:25461:locator)<ec><v0>:1024 [Coordinator]
basicServer  | 10.25.3.192(basicServer:25546)<v1>:1025

一切就绪后,即可通过 Maven 启动客户端应用:

mvn spring-boot:run

6. 核心配置

6.1. Region 与实体映射

Region 是 Geode 中的核心数据结构,类似于关系型数据库中的“表”。

我们定义一个 Author 实体,并通过注解映射到名为 Authors 的 Region:

@Region("Authors")
public class Author {
    @Id
    private Long id;
    
    private String firstName;
    private String lastName;
    private int age;

    // getter / setter 省略
}

关键注解说明:

  • @Region("Authors"):声明该类对应 Geode 中的 /Authors Region
  • @Id:标记主键字段,用于唯一标识对象

6.2. 启用实体驱动的 Region 创建

为了让应用启动时自动在服务端创建 Region,需在主类上添加:

@EnableEntityDefinedRegions(basePackageClasses = Author.class)
@EnableClusterConfiguration
@ClientCacheApplication
@SpringBootApplication 
public class ClientCacheApp {
    // ...
}
  • @EnableEntityDefinedRegions:扫描带有 @Region 的实体类
  • @EnableClusterConfiguration:允许客户端向集群推送配置(如 Region 创建)

重启应用后,在 gfsh 中执行:

gfsh> list regions

输出:

List of regions
---------------
Authors

✅ Region 已自动创建,无需手动建表。

6.3. 使用 Repository 实现 CRUD

Spring Data Geode 完全兼容 Spring Data 的 Repository 模式。

定义 AuthorRepository

public interface AuthorRepository extends CrudRepository<Author, Long> {
}

然后在主类上启用 GemFire 风格的 Repository 扫描:

@EnableGemfireRepositories(basePackageClasses = AuthorRepository.class)
// 其他注解...
public class ClientCacheApp {
    // ...
}

现在就可以注入 AuthorRepository 使用标准方法:

  • save():保存或更新
  • findById():按主键查询
  • deleteById():删除
  • 以及其他继承自 CrudRepository 的方法

简单粗暴,和操作数据库一样。

6.4. 索引配置

Geode 查询性能依赖索引。Spring Data Geode 支持通过注解自动创建索引。

启用索引功能

@EnableIndexing
// 其他注解...
public class ClientCacheApp {
    // ...
}

在实体上添加索引

public class Author {
    @Id
    private Long id;

    @Indexed
    private int age;

    // 其他字段...
}
  • @Id → 自动创建主键索引(Hash)
  • @Indexed → 为 age 创建范围索引(Range)

重启应用后,查看索引:

gfsh> list indexes

输出示例:

Member Name | Region Path |       Name        | Type  | Indexed Expression | From Clause | Valid Index
----------- | ----------- | ----------------- | ----- | ------------------ | ----------- | -----------
basicServer | /Authors    | AuthorsAgeKeyIdx  | RANGE | age                | /Authors    | true
basicServer | /Authors    | AuthorsIdHashIdx  | RANGE | id                 | /Authors    | true

✅ 索引已自动创建并生效。

📌 提示:对于文本字段,可使用 @LuceneIndexed 创建 Lucene 全文索引。

6.5. 持续查询(Continuous Query)

持续查询(CQ)是一种订阅机制,允许客户端在数据变更时收到实时通知。

创建服务类并监听 CQ

@Service
public class AuthorService {

    @ContinuousQuery(query = "SELECT * FROM /Authors a WHERE a.id = 1")
    public void process(CqEvent event) {
        System.out.println("Author #" + event.getKey() + " updated to " + event.getNewValue());
    }
}
  • id=1 的 Author 被修改时,process 方法将被触发
  • CqEvent 包含旧值、新值、操作类型等信息

启用订阅支持

在主类上开启客户端订阅:

@ClientCacheApplication(subscriptionEnabled = true)
// 其他注解...
public class ClientCacheApp {
    // ...
}

⚠️ 缺少 subscriptionEnabled = true,CQ 将无法工作。

7. 其他实用注解

Spring Data Geode 提供了一系列“开箱即用”的注解,简化高级功能配置。

7.1. @PeerCacheApplication

将应用变为集群中的 Peer 节点(而非纯客户端),可直接参与数据存储与分发:

@PeerCacheApplication
@SpringBootApplication
public class PeerApp {
    // ...
}

✅ 自动创建内嵌缓存实例,加入集群。

7.2. @CacheServerApplication

让应用同时作为 Peer + Server,对外提供缓存服务:

@CacheServerApplication
@SpringBootApplication
public class CacheServerApp {
    // ...
}

适合需要嵌入式缓存服务的微服务架构。

7.3. @EnableHttpService

为 Peer 或 Server 启用内嵌 HTTP 服务(默认端口 7070):

@EnableHttpService
@PeerCacheApplication
public class HttpEnabledApp {
    // ...
}

可用于暴露 JMX、管理接口或自定义 REST 端点。

7.4. @EnableLogging

开启 Geode 日志输出,支持自定义级别和文件:

@EnableLogging(logLevel = "INFO", logFile = "geode-client.log")
@ClientCacheApplication
public class LoggingApp {
    // ...
}

调试时非常有用。

7.5. @EnablePdx

启用 Geode 的 PDX(Portable Data eXchange)序列化机制,提升跨语言互操作性和性能:

@EnablePdx
@ClientCacheApplication
public class PdxApp {
    // ...
}

✅ 推荐启用,尤其在混合技术栈环境中。

7.6. @EnableSsl 与 @EnableSecurity

  • @EnableSsl:开启 TCP 层 SSL 加密
  • @EnableSecurity:启用认证与授权(需配合 Security Manager)
@EnableSsl
@EnableSecurity
@ClientCacheApplication
public class SecureApp {
    // ...
}

生产环境必备。

8. 总结

本文通过 Spring Data Geode 快速构建了一个功能完整的 Geode 客户端应用,涵盖了:

✅ 核心流程:依赖引入 → 客户端配置 → 实体映射 → Repository 操作
✅ 高级特性:自动 Region 创建、索引管理、持续查询、日志、SSL 等
✅ 多种部署模式:Client、Peer、Server 自由切换

所有示例代码已整理至 GitHub:

👉 https://github.com/tech-tutorial/spring-data-geode-demo

如果你正在构建高并发、低延迟的缓存系统,Spring Data Geode 是一个值得考虑的技术选型。简单、强大、与 Spring 生态无缝集成。


原始标题:Intro to Spring Data Geode