如何在 Spring Boot 中使用 Hazel Cast 实例

问题描述 投票:0回答:1

我想在我的 Spring Boot 应用程序中使用 Hazel Cast,但出现以下错误 无法自动装配。有多个“HazelcastInstance”类型的 bean。 豆子: hazelcastInstance(HazelcastClientConfiguration.class) hazelcastInstance(HazelcastServerConfiguration.class)

在下面一行: @Autowired 私有 HazelcastInstance hazelcastInstance;

    <dependency>
        <groupId>com.hazelcast</groupId>
        <artifactId>hazelcast-spring</artifactId>
        <version>5.3.1</version>
    </dependency>
spring-boot hazelcast
1个回答
0
投票

错误消息意味着您为 Hazelcast 对象定义了两个 bean。

  1. Hazelcast 客户端
  2. Hazelcast 服务器

你应该只吃 1 颗豆子。类路径中可能有 hazelcast.yaml 和 hazelcast-client.yml 文件。您应该只有一个文件

我将为您提供一个在您的项目中运行的嵌入式 HZ 服务器的示例。您可能需要更改 pom.xml 以仅包含 hazelcast 依赖项。我正在使用

<dependency>
  <groupId>com.hazelcast</groupId>
  <artifactId>hazelcast</artifactId>
  <version>5.3.2</version>
</dependency>

现在创建此文件src/main/resources/hazelcast.yaml

hazelcast:
  network:
    join:
      multicast:
        enabled: true

spring-boot-autoconfigure项目将自动发现yaml文件并为您创建一个嵌入式服务器。 然后在你的代码中有这样的东西

@SpringBootApplication
public class HzSpringTutorialApplication implements CommandLineRunner {

    Logger logger = LoggerFactory.getLogger(HzSpringTutorialApplication.class);
    @Autowired
    HazelcastInstance hazelcastInstance;

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

    @Override
    public void run(String... args) {
        IMap<Long, String> map = hazelcastInstance.getMap("data");
        for (long i = 0; i < 10; i++) {
            String value = map.get(i);
            logger.info("Map value : {} ", value);
        }
    }
}

在此代码中,您将连接到嵌入式 HZ 成员。

如果需要 SpringBoot 连接到现有的 HZ 集群,则需要删除 hazelcast.yaml 文件并创建新的 hazelcast-client.yml 文件用于 HZ 客户端配置

© www.soinside.com 2019 - 2024. All rights reserved.