简体   繁体   English

响应式Spring Data Mongodb查询在不应该返回旧数据的情况下

[英]Reactive Spring Data Mongodb Query is returning old data when it should not

I am trying to only fetch newly created messages from a reactive Mongodb repository using Spring Data. 我正在尝试仅使用Spring Data从反应性Mongodb存储库中获取新创建的消息。

The client is fetching the messages via SSE. 客户端正在通过SSE获取消息。 I am using an "after"-query, which should only return messages which were sent after "LocalDateTime.now()". 我正在使用“之后”查询,该查询仅应返回在“ LocalDateTime.now()”之后发送的消息。

Unfortunately the SSE is pushing out old messages which are older than "now", too. 不幸的是,上证所也推出了比“现在”还早的旧消息。 I have no clue why it returns those old messages. 我不知道为什么它返回那些旧消息。

My controller method: 我的控制器方法:

    @GetMapping(value = "/receiving-sse", produces = "text/event-stream")
    public Flux<Message> streamEvents() {
        Mono<String> username = getUsernameFromAuth();

        Flux<Message> message = findOrCreateUser(username)
                .flatMapMany(user -> messageRepository
                        .findAllBySenderIdOrReceiverIdAndSentAtAfter(user.getId(), user.getId(), LocalDateTime.now()));

        Flux<Message> heartBeat = Flux.interval(Duration.ofSeconds(30)).map(sequence -> {
            Message heartBeatMessage = new Message();
            heartBeatMessage.setHeartbeat(true);
            return heartBeatMessage;
        });

        return Flux.merge(message, heartBeat);
    }

My repository: 我的资料库:

public interface MessageRepository extends ReactiveMongoRepository<Message, String> {

    Flux<Message> findAllByReceiverId(String receiverId);

    @Tailable
    Flux<Message> findAllBySenderIdOrReceiverIdAndSentAtAfter(String senderId, String receiverId, LocalDateTime sentAt);

    Flux<Message> findAllBySenderId(String senderId);

    Flux<Message> findAllByIdIn(Collection<String> ids);

}

And my document: 而我的文件:

@Data
@Document
public class Message {

    private String id;

    private LocalDateTime sentAt;

    private String message;

    private boolean heartbeat;

    @DBRef
    private User sender;

    @DBRef
    private User receiver;
}

Any hints on why the repo is fetching messages that have a "sentAt" older than "LocalDateTime.now()" is much appreciated. 十分感谢有关回购为何要提取具有比“ LocalDateTime.now()”更旧的“ sentAt”的消息的任何提示。

Problem is in LocalDateTime.now() . 问题出在LocalDateTime.now() LocalDateTime creates a time during initialization of a Flux<Message> message variable. LocalDateTime在初始化Flux<Message> message变量期间创建一个时间。

You need to replace it with construction like Mono.defer() . 您需要将其替换为Mono.defer()类的Mono.defer() It will create LocalDateTime in every subscribe. 它将在每个订阅中创建LocalDateTime。

More you can read here 更多你可以在这里阅读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM