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

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

问题描述

在我们的架构中,我们有一个 Redis 服务器,用于缓存和发布事件.

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

我的问题如下

  • 我有一条名为CustomerUpdate"的消息
  • 我有 1 个应用程序正在收听此消息
  • 正在执行此应用程序的 3 个实例(服务器)以实现可扩展性
  • 1 个数据库实例正在运行
  • 此消息的处理程序之一将更新数据库
  • 其他一些处理程序将清除内存缓存或对实例执行本地操作

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

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).如果 value 已经以 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 是单线程的,因此如果消息被其他服务器接收,所有其他服务器都会返回 false.

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天全站免登陆