[英]Correct Use of Spring Boot Hazelcast Auto-Configuration with @SpringAware MapLoader
我有一个使用Spring Boot 2.4.1和Hazelcast 4.1.1的项目。 我正在尝试使用 Spring 引导自动配置来设置分布式 map,并使用 JpaRepository 进行读取以填充 map。 I've added application.yaml and hazelcast.yaml and provided an implementation of com.hazelcast.map.MapLoader
and com.hazelcast.map.MapLoaderLifecycleSupport
annotated with @SpringAware
. hazelcast 实例启动正常,但从未调用 MapLoader。 hazelcast 文档仅提供 Spring XML 配置示例
com.hazelcast.config.MapConfig
和com.hazelcast.config.Config
?@SpringAware
与 MapLoader 一起使用?您可以提供的任何指导将不胜感激。 以下是我到目前为止所尝试的:
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() {
}
}
一种方法是拥有一个实现MapStoreFactory
的@Component
class 。 工厂需要执行:
MapLoader newMapStore(String mapName, Properties properties)
并且可以使用 map 名称来查找相关的 bean。
然后在您的@Configuration
中,您可以注入工厂,并使用它在地图的 map 存储配置 object 上设置工厂实现。
这也可能是一个解决方案,虽然我没有尝试过。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.