如何确保我的事件仅由我的一个应用实例处理? [英] How to make sure my event is handled by only one instance of my app?

查看:85
本文介绍了如何确保我的事件仅由我的一个应用实例处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的体系结构中,我们有一个Redis服务器,用于缓存和发布事件。

In our architecture we have a Redis server we use for caching and for publishing event.

我的问题是以下


  • 我有一条名为 CustomerUpdate的消息

  • 我有1个应用程序正在监听此消息

  • 为了可伸缩性,正在执行此应用程序的3个实例(服务器)

  • 1个数据库实例正在运行

  • 该消息的处理程序之一将更新数据库

  • 某些其他处理程序将擦除内存缓存或对实例执行本地操作

  • I have an message called "CustomerUpdate"
  • I have 1 application listening to this message
  • 3 instance (server) of this application are being executed for scalability
  • 1 instance of the database is running
  • One of the handler for this message will update the database
  • Some other handler will erase memory cache or do something local to the instance

是否有任何模式可确保应用程序的每个实例都不更新数据库?

Is there any pattern for making sure that the database is not updated by every instance of the application?

推荐答案

您可以使用redis键/值作为阻止程序。当实例从订阅中获取消息时,请在Redis中执行LUA脚本,以检查该进程是否已经存在。

You can use a redis key/value as blocker. When instances receive message from subcription excute LUA script in redis to check if process already exist for it.

服务器从订阅中获取消息
使用redis脚本事务来检查如果该消息已经存在一个锁(例如get receiveMessageId:XXX之类的东西)。如果值已经以false退出,则在服务器上不执行任何操作。如果该值不存在,请设置它并返回true。然后,您的服务器可以处理该消息。

Server receive message from subscription Use redis script transaction to check if there already exist a lock for this message (something Like get receiveMessageId:XXX). If value already exit with false then do nothing on server. If the value doesn't exist set it and return true. Then your server can process the message.

由于Redis是单线程的,因此如果其他服务器接收了该消息,则其他所有服务器都会得到错误消息。

As Redis is single threaded all other server will get a false if message is taken by an other server.

要删除此密钥,可以将TTL设置为足够大,以避免从其他服务器收到消息。

To remove this key you can set a TTL big enought to avoid taken message from other servers.

这篇关于如何确保我的事件仅由我的一个应用实例处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆