简体   繁体   English

如何在两个节点之间使用 HazelCast 同步方法?

[英]How to synchronize method with HazelCast between two nodes?

There is Spring Boot project.Spring Boot项目。 Project works on two nodes.项目在两个节点上工作。 I have method for send message mail with scheduler.我有使用调度程序发送消息邮件的方法。 The message is sent 2 times, since two nodes are working.该消息发送 2 次,因为两个节点都在工作。 How can I use HazelCast to configure the method so that it works once, only by one, more optimal node?如何使用HazelCast配置该方法,使其工作一次,只能由一个更优化的节点运行? There is very little documentation and articles on the net.网络上的文档和文章很少。 I have already added HazelCast to the project, and the nodes see each other.我已经将HazelCast添加到项目中,节点之间可以看到彼此。

HazelCast.yaml : HazelCast.yaml :

hazelcast:
  network:
    join:
      multicast:
        enabled: true

Gradle :摇篮

    implementation group: 'com.hazelcast', name: 'hazelcast-all', version: '4.2'

ForExampleMyMethodForSendMail : ForExampleMyMethodForSendMail

@Scheduled(cron = "0 0 9 * * ?")
public void senMail(MailDTO mailDTO) {
   mailService.sendMail(mailDTO);
}

Use Hazelcast distributed lock feature with your own code to ensure you send mail only once.将 Hazelcast 分布式锁定功能与您自己的代码一起使用,以确保您只发送一次邮件。 https://docs.hazelcast.com/imdg/4.2/cp-subsystem/fencedlock.html https://docs.hazelcast.com/imdg/4.2/cp-subsystem/fencedlock.html

I have created a distributed map that is visible with two nodes at the same time (this feature is provided by HazelCast ).我创建了一个distributed map ,该distributed map同时对两个nodes可见(此功能由HazelCast提供)。 After that, I began to put the key value in this map according to the type of the name of the action and the time of the action.在那之后,我开始把key value根据的类型在这个地图name的动作和time的动作。 So the second node looked into the map, and if the action was already performed, it no longer performed it.所以第二个节点查看地图,如果操作已经执行,则不再执行。 So I solved the problem with duplicate messages.所以我解决了重复消息的问题。

I create distributed map:我创建分布式地图:

@Configuration
public class HazelCastConfiguration {

    @Bean
    public Config hazelCastConfig() {
        return new Config();
    }

    @Bean
    public HazelcastInstance hazelcastInstance(Config hazelCastConfig) {
        return Hazelcast.newHazelcastInstance(hazelCastConfig);
    }

    @Bean
    public Map<String, LocalDateTime> timeMap(@Qualifier("hazelcastInstance") HazelcastInstance hazelcastInstance) {
        return hazelcastInstance.getMap("hazelcastTimeMap");
    }
}

And then I use AutoWired for work with map:然后我使用 AutoWired 处理地图:

private Map<String, LocalDateTime> timeMap;

@AutoWired
public void setTimeMap(Map<String, LocalDateTime> timeMap) {
        this.timeMap = timeMap;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM