1. 概述
本文将重点介绍 如何将 Spring Data API 与 Apache Ignite 平台集成。关于 Apache Ignite 的基础知识,可参考我们的入门指南。
2. Maven 依赖配置
除了现有依赖外,需添加 Spring Data 支持模块:
<dependency>
<groupId>org.apache.ignite</groupId>
<artifactId>ignite-spring-data</artifactId>
<version>${ignite.version}</version>
</dependency>
ignite-spring-data
组件可从 Maven 中央仓库 获取。
3. 数据模型与仓库
我们将构建一个通过 Spring Data API 将员工数据存入 Ignite 缓存的示例应用。
EmployeeDTO
POJO 结构如下:
public class EmployeeDTO implements Serializable {
@QuerySqlField(index = true)
private Integer id;
@QuerySqlField(index = true)
private String name;
@QuerySqlField(index = true)
private boolean isEmployed;
// getters, setters
}
✅ @QuerySqlField
注解使字段可通过 SQL 查询
接下来创建持久化仓库:
@RepositoryConfig(cacheName = "baeldungCache")
public interface EmployeeRepository
extends IgniteRepository<EmployeeDTO, Integer> {
EmployeeDTO getEmployeeDTOById(Integer id);
}
⚠️ 关键点:
- Apache Ignite 使用自定义的
IgniteRepository
(继承自 Spring Data 的CrudRepository
) - 通过
@RepositoryConfig
将仓库映射到 Ignite 的baeldungCache
缓存 - 支持标准 CRUD 操作,但部分无 ID 的操作受限(测试部分详述)
4. Spring 配置
创建 Spring 配置类:
@Configuration
@EnableIgniteRepositories
public class SpringDataConfig {
@Bean
public Ignite igniteInstance() {
IgniteConfiguration config = new IgniteConfiguration();
CacheConfiguration cache = new CacheConfiguration("baeldungCache");
cache.setIndexedTypes(Integer.class, EmployeeDTO.class);
config.setCacheConfiguration(cache);
return Ignition.start(config);
}
}
配置要点:
@EnableIgniteRepositories
启用 Ignite 仓库支持igniteInstance()
方法创建 Ignite 实例并注入集群setIndexedTypes()
为缓存设置 SQL 模式
5. 仓库测试
注册配置并获取仓库实例:
AnnotationConfigApplicationContext context
= new AnnotationConfigApplicationContext();
context.register(SpringDataConfig.class);
context.refresh();
EmployeeRepository repository = context.getBean(EmployeeRepository.class);
创建并保存员工对象:
EmployeeDTO employeeDTO = new EmployeeDTO();
employeeDTO.setId(1);
employeeDTO.setName("John");
employeeDTO.setEmployed(true);
repository.save(employeeDTO.getId(), employeeDTO);
❌ 重要限制:
标准 CrudRepository.save(entity)
等操作暂不支持!
原因:集群中生成的 ID 无法保证唯一性。
✅ 替代方案:
save(key, value)
save(Map<ID, Entity> values)
deleteAll(Iterable<ID> ids)
通过自定义方法获取数据:
EmployeeDTO employee = repository.getEmployeeDTOById(employeeDTO.getId());
System.out.println(employee);
输出结果:
EmployeeDTO{id=1, name='John', isEmployed=true}
其他查询方式:
- IgniteCache API:
IgniteCache<Integer, EmployeeDTO> cache = ignite.cache("baeldungCache"); EmployeeDTO employeeDTO = cache.get(employeeId);
- 标准 SQL:
SqlFieldsQuery sql = new SqlFieldsQuery( "select * from EmployeeDTO where isEmployed = 'true'");
6. 总结
本教程通过实战示例演示了 Spring Data 与 Apache Ignite 的集成方案,重点包括:
- 使用 Spring Data API 操作 Ignite 缓存
- 仓库配置与查询实现
- 避免常见 ID 生成问题的解决方案
完整代码示例见 GitHub 项目。