我需要将监听器附加到数据库中的表 一旦在表中执行 CRUD 操作(预监听器和后监听器),它应该调用 spring boot 方法 该条目可以来自任何来源 我怎样才能在 Spring Boot 中做到这一点?
最佳答案
如果实体可以从任何来源创建 - 例如手动插入 - 这超出了正在运行的应用程序的范围和上下文。
您所描述的内容被称为 CDC (change data capture)模式。
要在这种情况下实现 CDC,您需要使用底层数据库的工具 - 例如触发器。
据我所知,这是用 MongoDb 标记的 - 触发器不是一个选项,因为 mongodb 不支持触发器。
如果您使用的是 MongoDb v3.6+,您可以利用新的 Change Streams特征。这是official example使用 Java。
Change streams allow applications to access real-time data changes without the complexity and risk of tailing the oplog. Applications can use change streams to subscribe to all data changes on a single collection, a database, or an entire deployment, and immediately react to them. Because change streams use the aggregation framework, applications can also filter for specific changes or transform the notifications at will.
如果您使用的是早期版本的 MongoDb,您可以监控 oplog或使用tailable cursors具有上限的集合。
另一种方法是研究第三方解决方案,将数据库中发生的所有事情转变为事件流 - 例如 debezium .
关于spring - 使用 Spring Boot 的数据库事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51116036/