Why does Spring Data MongoDB not expose events for update…(…) methods?

后端 未结 3 1625
情话喂你
情话喂你 2021-01-07 09:37

It appears that the update for mongoOperations do not trigger the events in AbstractMongoEventListener.

This post indicates that wa

3条回答
  •  终归单人心
    2021-01-07 09:56

    You can listen to database changes, even the changes completely outside your program (MongoDB 4.2 and newer).

    (code is in kotlin language. same for java)

    @Autowired private lateinit var op: MongoTemplate
    
    @PostConstruct
    fun listenOnExternalChanges() {
        Thread {
            op.getCollection("Item").watch().onEach {
                if(it.updateDescription.updatedFields.containsKey("name")) {
                    println("name changed on a document: ${it.updateDescription.updatedFields["name"]}")
                }
            }
        }.start()
    }
    

    This code only works when replication is enabled. You can enable it even when you have a single node:

    Add the following replica set details to mongodb.conf (/etc/mongodb.conf or /usr/local/etc/mongod.conf or C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg) file

    replication:
      replSetName: "local"
    

    Restart mongo service, Then open mongo console and run this command:

    rs.initiate()
    

提交回复
热议问题