我有一个使用Spring Boot 2.4.1和Hazelcast 4.1.1的项目。我正在尝试使用 Spring Boot 自动配置来设置分布式地图,并使用 JpaRepository 读取来填充地图。我添加了application.yaml和hazelcast.yaml并提供了一个实现com.hazelcast.map.MapLoader
并com.hazelcast.map.MapLoaderLifecycleSupport
用@SpringAware
. hazelcast 实例启动正常,但从未调用 MapLoader。hazelcast 文档仅提供 Spring XML 配置示例
- 是否可以将 Hazelcast 的 Spring Boot 自动配置与 MapLoader 结合使用,还是我需要提供自己的
com.hazelcast.config.MapConfig
和com.hazelcast.config.Config
bean? - 如何使用
@SpringAware
MapLoader? - init 方法中应该包含什么?
- 我需要用 Hazelcast 上下文注册 Spring 上下文吗?
您可以提供的任何指导将不胜感激。以下是我到目前为止所尝试的:
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
...
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.hazelcast</groupId>
<artifactId>hazelcast-all</artifactId>
<version>4.1.1</version>
</dependency>
应用程序.yaml:
# datasource and JPA config omitted
spring:
hazelcast:
config: classpath:hazelcast.yaml
hazelcast.yaml
hazelcast:
cluster-name: hazelcast-cluster
map:
myResourceMap:
map-loader:
enabled: true
initial-mode: EAGER
class-name: com.dev.hz.MyResourceMaploader
地图加载器实现:
@SpringAware
public class MyResourceMapLoader implements MapLoader<Long, MyResource>, MapLoaderLifecycleSupport {
private final MyResourceRepository repo;
public MyResourceMapLoader(MyResourceRepository repo) {
this.repo = repo;
}
@Override
public MyResource load(Long key) {
return this.repo.findById(key).orElse(null);
}
@Override
public Map<Long, MyResource> loadAll(Collection<Long> keys) {
Map<Long, MyResource> myResourceMap = new HashMap<>();
for (Long key : keys) {
MyResource myResource = this.load(key);
if (myResource != null) {
myResourceMap.put(key, myResource);
}
}
return myResourceMap;
}
@Override
public Iterable<Long> loadAllKeys() {
return this.repo.findAllIds();
}
@Override
public void init(HazelcastInstance hazelcastInstance, Properties properties, String mapName) {
}
@Override
public void destroy() {
}
}