监听 MongoDB 文档的字段值变化,使用 Spring。

huangapple go评论79阅读模式
英文:

Listen to field's value change of MongoDB's document with Spring

问题

根据我的用例,在用户注册到我的网站时,将在用户集合中创建以下文档。

{
  "_id": "xxxx",
  "name": "xxxx",
  "hash": "xxxx",
  "salt": "xxxx",
  "approved": false
}

只有在管理员批准后,用户的注册请求才会被接受。管理员不会在注册后立即批准,通常需要一天以上的时间来查看注册请求列表。在管理员批准后,上述文档将会变成如下:(approved 字段变为 true)

{
  "_id": "xxxx",
  "name": "xxxx",
  "hash": "xxxx",
  "salt": "xxxx",
  "approved": true
}

下面这两个函数是使用 Spring 实现的。

public void createRegistrationRequest(User obj) {
   // 逻辑
}

public void executeAfterApproval() {
   // 逻辑
}

approved 字段的值变为 true 时,应该执行 executeAfterApproval() 方法。如何监听此字段的值变化并触发方法在 Spring 中的执行?

附注:实际上,原始用例有点难以解释,因为它与内部情景更相关。因此,将情景翻译为用户注册,以便更容易理解问题。

英文:

According to my use-case, whenever a user is registered to my site, the following document will be created in User collection.

{
 "_id": "xxxx",
 "name": "xxxx",
 "hash": "xxxx",
 "salt": "xxxx",
 "approved": false
}

Only after the admin's approval, the user's registration request will be accepted. The admin won't approve immediately after the registration and generally takes more than a day to look at the registration request list. After admin's approval, the above document changes like below: (approved field changes to true)

{
 "_id": "xxxx",
 "name": "xxxx",
 "hash": "xxxx",
 "salt": "xxxx",
 "approved": true
}

The below two functions are implemented with spring.

public void createRegistrationRequest(User obj) {
   // logic
}

public void executeAfterApproval() {
   // logic
}

The executeAfterApproval() method should execute when the approved field value changes to true. How to listen to this field's value change and trigger the method's execution with Spring?

PS: Actually, the original use-case is a bit difficult to explain as it is more related to internal scenarios. So, translated the scenario as user registration for an easy understanding of the problem.

答案1

得分: 1

你应该使用MongoDB的变更流(change streams)。如果你正在使用Spring Data,它对命令式和响应式驱动程序都有支持。你可以使用变更流来监听用户集合的变更,并且可以应用一些条件来使其更加具体。

查看:https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#change-streams

英文:

You should use MongoDB change streams. If you are using Spring Data it has support for both imperative and reactive drivers. You can use a change stream for listening to User collection changes and apply some criterias to be more specific.

Check: https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/#change-streams

huangapple
  • 本文由 发表于 2020年9月6日 01:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63756793.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定