我正在从事Spring Boot项目。在那儿,我有一个名为ProductMap的实体,我想保留在缓存中。我使用MapLoader并按如下所示定义了地图的配置。
@Bean
public Config hazelcastConfig() {
return new Config().setInstanceName("hazelcast-instance").addMapConfig(
new MapConfig().setName("ProductMap")
.setMapStoreConfig(
new MapStoreConfig().setEnabled(true).setInitialLoadMode(MapStoreConfig.InitialLoadMode.EAGER)
.setClassName("com.hazelcast.example.HzTest.config.ProductMapLoader")
));
}
ProductMap实体:
@Data
@Entity
@KeySpace("ProductMap")
@Table
public class ProductMap implements Serializable {
@Id
@org.springframework.data.annotation.Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer Id;
private String name;
private Integer category;
private Integer productType;
}
ProductMapLoader:
@Log4j2
@Component
public class ProductMapLoader implements MapLoader<Integer, ProductMap>, ApplicationContextAware {
private static ProductMapRepository productMapRepository;
@Override
public synchronized ProductMap load(Integer integer) {
System.out.println("Load::" + integer);
return productMapRepository.findById(integer).get();
}
@Override
public synchronized Map<Integer, ProductMap> loadAll(Collection<Integer> collection) {
Map<Integer, ProductMap> result = new HashMap<>();
for (Integer key : collection) {
ProductMap productMap = this.load(key);
if (productMap != null) {
result.put(key, productMap);
}
}
return result;
}
@Override
public synchronized Iterable<Integer> loadAllKeys() {
System.out.println("load all keys" + productMapRepository);
return productMapRepository.findAllProdMapKeys();
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
productMapRepository = applicationContext.getBean(ProductMapRepository.class);
}
}
我正在启动时加载缓存,
@PostConstruct
public void Init() {
IMap map = hazelcastInstance.getMap("ProductMap"); // this will load the cache
}
还创建了一个HazelcastRepository,
public interface ProductMapKvRepo extends KeyValueRepository<ProductMap, Integer> {
List<ProductMap> findByProductType(Integer productType);
}
在我的一种服务方法中,它调用productMapKvRepo.findAll()
和productMapKvRepo.findByProductType(1).
,但是存储库仍在查询数据库。
Hibernate: select productmap0_.id as id1_0_, productmap0_.category as category2_0_, productmap0_.name as name3_0_, productmap0_.product_type as product_4_0_ from product_map productmap0_
Hibernate: select productmap0_.id as id1_0_, productmap0_.category as category2_0_, productmap0_.name as name3_0_, productmap0_.product_type as product_4_0_ from product_map productmap0_ where productmap0_.product_type=?
谁能告诉我这是怎么回事,我该怎么办?
您的日志表明您的Spring Data存储库是Hibernate支持的,这意味着您的项目配置错误。 Spring Data Hazelcast不使用Hibernate从Hazelcast IMDG集群中读取数据。
如果打算(最有可能)使用Hibernate,则应考虑将其本机二级缓存功能与Hazelcast一起使用,而不是将Spring Data存储库包装在MapLoader中。您可以找到示例here。
但是,如果要对MapLoader应用read-through缓存模式,则需要使用spring-data-hazelcast
工件直接从Hazelcast群集中读取数据。