java - Spring Data MongoRepository save(T) 不工作......有时

标签 java mongodb spring-boot spring-data

所以我正在使用这个小 Angular + Java + Spring Boot + MongoDB 应用程序。最近它有很多 Action (阅读:代码修改),但数据访问类在很大程度上没有受到 AFAIK 的影响。
但是,似乎 MongoRepository突然决定停止坚持我的更改 save()转到 DB。

检查mongod.log这是我在 save() 时看到的作品:

2018-04-11T15:04:06.840+0200 I COMMAND  [conn6] command pdfviewer.bookData command: find { find: "bookData", filter: { _id: "ID_1" }, limit: 1, singleBatch: true } planSummary: IDHACK keysExamined:1 docsExamined:1 idhack:1 cursorExhausted:1 keyUpdates:0 writeConflicts:0 numYields:1 nreturned:1 reslen:716 locks:{ Global: { acquireCount: { r: 4 } }, Database: { acquireCount: { r: 2 } }, Collection: { acquireCount: { r: 2 } } } protocol:op_query 102ms
2018-04-11T17:30:19.615+0200 I WRITE    [conn7] update pdfviewer.bookData query: { _id: "ID_1" } update: { _class: "model.BookData", _id: "ID_1", config: { mode: "normal", offlineEnabled: true }, metadata: { title: "PDFdePrueba3pag   copia  6 ", ...}, downloaded: false, currentPageNumber: 2, availablePages: 3, bookmarks: [], stats: { _id: "c919e517-3c68-462c-8396-d4ba391762e6", dateOpen: new Date(1523460575872), dateClose: new Date(1523460575951), timeZone: "+2", ... }, ... } keysExamined:1 docsExamined:1 nMatched:1 nModified:1 keyUpdates:0 writeConflicts:1 numYields:1 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 2 } }, Collection: { acquireCount: { w: 2 } } } 315ms
2018-04-11T17:30:19.615+0200 I COMMAND  [conn7] command pdfviewer.$cmd command: update { update: "bookData", ordered: false, updates: [ { q: { _id: "ID_1" }, u: { _class: "model.BookData", _id: "ID_1", config: { mode: "normal", offlineEnabled: true }, metadata: { title: "PDFdePrueba3pag   copia  6 ", ...}, downloaded: false, currentPageNumber: 2, availablePages: 3, bookmarks: [], stats: { _id: "c919e517-3c68-462c-8396-d4ba391762e6", dateOpen: new Date(1523460575872), dateClose: new Date(1523460575951), timeZone: "+2", ... }, ... }, upsert: true } ] } keyUpdates:0 writeConflicts:0 numYields:0 reslen:55 locks:{ Global: { acquireCount: { r: 2, w: 2 } }, Database: { acquireCount: { w: 2 } }, Collection: { acquireCount: { w: 2 } } } protocol:op_query 316ms

这就是我在没有看到的时候看到的:

2018-04-11T18:13:21.864+0200 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:64271 #1 (1 connection now open)
2018-04-11T18:18:51.425+0200 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:64329 #2 (2 connections now open)
2018-04-11T18:19:06.967+0200 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:64346 #3 (3 connections now open)

通过 tail -f 1 在调试时记录在日志文件中,我已经看到当我的代码调用 findById() 时这些连接正确出现或 save() ,所以看起来该应用程序可以访问数据库。

这是(或多或少)相关的 Java 代码:

/* BookData.java */
@Document
public class BookData {

    @Id private String id;
    // Some more non-Id Strings...
    private Config config;
    private Metadata metadata;
    private Boolean downloaded;
    private Integer currentPageNumber;
    private int availablePages;
    private List<Bookmark> bookmarks;
    private StatsModel stats;

    @Transient private byte[] contents;

    public BookData() {}

    // getters and setters
}

/* BookDataRepository.java */
// MongoRepository comes from spring-boot-starter-parent-1.4.5.RELEASE
public interface BookDataRepository extends MongoRepository<BookData, String> {
    BookData findById(String id);
}

/* BookDataServiceImpl.java */
public BookData updateBookData(String id, BookData newData) {
    final BookData original = bookDataRepository.findById(id);
    if (original == null) {
        return null;
    }
    original.setCurrentPageNumber(Optional.ofNullable(newData.getCurrentPageNumber()).orElseGet(original::getCurrentPageNumber));
    // similar code for a couple other fields

    return bookDataRepository.save(original);
}

我在调试的时候已经经历了一百次,一切似乎都很好:

  • findById(id)正确返回预期的 BookData original对象:检查✓
  • newData包含用于更新的预期值:check ✓
  • 就在调用 save(original) 之前, original已使用 newData 正确修改值:检查✓
  • save()执行没有错误:检查✓
  • save()返回一个新的 BookData正确更新的值:令我惊讶的是,检查✓
  • save() 之后返回,一个 db.bookData.find() Mongo Shell 中的查询显示值已更新:失败
  • save() 之后返回,BookData新调用 findById() 检索到的对象包含更新后的值:fail(有时会,有时不会)。

看起来 MongoDB 正在等待某种 flush() ,但这不是一个可以调用 saveAndFlush() 的 JPA 存储库而是。

任何想法为什么会发生这种情况?

编辑:版本(根据要求):

  • Java 8
  • Spring Boot 1.4.5
  • MongoDB 3.2.6
  • Windows 10

我还包括了BookData以上。

最佳答案

MongoDB 本质上是一个缓存存储,我的意思是,不能保证内容是最新的或必然正确的。我一直无法找到刷新时间的配置选项(但它们会在数据库本身中配置),但是 MongoDB 已经添加了一些功能,因此您可以选择快速+脏,或者慢+干净。如果您遇到此类问题,则此“新鲜度”因素很可能是您的问题。 (即使你没有运行分布式,请求确认和请求提交之间也存在时间差异)

这是一个关于“干净阅读”的帖子链接(以下引用中的关键点)

http://www.dagolden.com/index.php/2633/no-more-dirty-reads-with-mongodb/

I encourage MongoDB users to place themselves (or at least, their application activities) into one of the following groups:

"I want low latency" – Dirty reads are OK as long as things are fast. Use w=1 and read concern 'local'. (These are the default settings.) "I want consistency" – Dirty reads are not OK, even at the cost of latency or slightly out of date data. Use w='majority' and read concern 'majority. use MongoDB v1.2.0;

my $mc = MongoDB->connect(
    $uri,
    {
        read_concern_level => 'majority',
        w => 'majority',
    }
);

进一步阅读可能有用也可能没用

更新

如果在多线程环境中运行,请确保您的线程不会践踏其他线程的更新。您可以通过将系统或查询日志记录级别配置为 5 来验证是否发生这种情况。 https://docs.mongodb.com/manual/reference/log-messages/#log-messages-configure-verbosity

关于java - Spring Data MongoRepository save(T) 不工作......有时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49780827/

相关文章:

java - 创建 Deployment 时 Kubernetes "fatal alert: protocol_version"错误

java - 在高峰时间,请求在 Tomcat 8 中花费太多时间

spring-boot - 手动验证 keycloak 访问 token

java - 为什么我会出现空指针异常?

java Lucene最佳匹配不是精确匹配

mongodb - 在 MongoDB 中投票

node.js - 如何使用 mongodb 查询从深度集合中删除文档?

tomcat - Windows 10 上的 Spring STS Spring Tools Suite 端口问题 Tomcat

java - 忽略 "Content is not allowed in trailing section"SAXException

java - 将 Redis ByteString 转换为 BasicDBObject