mongodb-脏数据问题
采用多线程后, 发现最大的问题是redis和mongodb的脏数据问题
1, upsert 的脏数据问题
多线程对同一个collect进行upsert操作时, 会引发并发脏数据问题, 最开始的解决方案是 在之前和之后 使用 LOCK.lock() 和LOCK.unlock(), 后来无意看到一篇博客: http://www.bkjia.com/sjkqy/952435.html, 返现在springboot操作使用MongoTemplate时, 只需要在 查询的条件上添加 @Indexed 就可以解决
2, 使用乐观锁进行控制:
import org.springframework.data.annotation.Version; @Version protected Long version;
3, findAndModify 操作是原子性的
UserState userState = mongoTemplate.findAndModify(new Query(Criteria.where("userId").is(userId)), update, new FindAndModifyOptions().returnNew(true).upsert(true), UserState.class);