【问题标题】:Update a database continuously不断更新数据库
【发布时间】:2019-03-24 21:34:16
【问题描述】:

我是软件开发的新手,正在构建一个 Angular TS 应用程序来管理队列中的人员,我使用 Firebase/Firestore 作为我的后端。用户有 3 种状态:用户正在等待、被呼叫或不在队列中。当用户被呼叫时,他/她必须在 10 秒前回复“出席”,否则他/她会自动被移出队列。

我尝试通过每秒激活一个服务来实现最后一个规范,该服务将检查是否已超过时间限制,并在这种情况下将用户状态更新为相应的 Firestore 文档中的“队列外”。

user.service.ts

 unqueueUser(): any {
 const actualTime = new Date();

 this.afs.collection<User>('users', ref =>
 ref.orderBy('status.call_moment.time_lim', 'asc')
   .where('status.value', '==', "CALLED")
   .where('status.call_moment.time_lim', '<=', actualTime))
   .snapshotChanges()
   .pipe(map((actions: DocumentChangeAction<User>[]) => {
      const indices = [];
      actions.map((a: DocumentChangeAction<User>) => {
        const data = a.payload.doc.data() as User;
        indices.push(data.id);
      });
      return indices;
    }))
    .subscribe(data => {
      for (const id of data) {
        return this.afs.doc(`users/${id}`)
        .update({
          'status.value': "OUT OF THE LINE",
        });
      }
    });
 }

user.component.ts

export class UserListComponent implements OnInit {
userList: User[];

ngOnInit() {
  this.userService.getUserList().subscribe(data => this.userList = data);

  setInterval(() => { this.userService.unqueueUser(); }, 1000);
 }
}

我的解决方案中最大的问题是很容易在半天的时间内达到读取操作的限制(而且我要处理一百个用户!)。

您知道更好的解决方案吗?让我知道您是否需要更多信息来解决问题。谢谢!

【问题讨论】:

  • 提供你试过的代码。
  • Firebase 的部分优点在于它是一个“实时”数据库并提供实时事件。这应该是相当直截了当的;每个用户都向他们的“状态”节点添加一个观察者。当它发生变化时,您的应用将收到一个事件(包含新状态)。在设备上启动一个 10 秒计时器,如果它们在该时间范围内没有响应,则将它们从队列中删除。但是,我们需要查看一些代码,或许还需要对问题进行更清晰的解释。请查看How to create a Minimal, Complete, and Verifiable example
  • 我编辑了帖子。
  • @Jay 能否提供一段代码,在您所说的设备上实现监听器和 10 秒计时器?
  • 现在您知道该做什么了 1) 将观察者添加到节点(AngularFire 中的 $watch(callback, context) )和 2) 创建一个计时器,您就有了方向。尝试为这两个任务编写一些代码,当你遇到困难时,发布一个问题,我们会看看!

标签: angularjs firebase firebase-realtime-database google-cloud-firestore google-cloud-functions


【解决方案1】:

与其每秒轮询 10 秒,不如在 10 秒结束时读取,如果有响应,您应该会获得 10 倍的读取次数。如果您需要它比这更灵敏一些,只需每 5 秒轮询一次。

【讨论】:

  • 是的,如果您只有一个用户需要管理,但并非所有用户都会同时被调用,那么这很好,因此该解决方案应该能够处理时间差异
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多