0

1)コントローラーコード(Symfony2フレームワーク):

    $em = $this->getDoctrine()->getEntityManager();

    // get latest toplist
    $last = $em->getRepository('RadioToplistBundle:Toplist')->findOneBy(
      array('number' => 'DESC')
    );

    // get current year and week of the year
    $week = date('W');
    $year = date('Y');

    // if:
    //   [case 1]: $last is null, meaning there are no toplists in the database
    //   [case 2]: $last->getYear() or $last->getWeek() do not match current
    //             year and week number, meaning that there are toplists in the
    //             database, but not for current week
    // then:
    //   create new toplist entity (for current week of current year)
    // else:
    //   do nothing (return)

    if($last && $last->getYear() == $year && $last->getWeek() == $week)
      return;
    else {
      $new = new Toplist();
      $new->setYear($year);
      $new->setWeek($week);
      $em->persist($new);
      $em->flush();
    }

このコードは、トップリストの結果(フロントエンド)またはトップリストのリスト(バックエンド)を表示するための各リクエストで実行されます。誰かがトップリストにアクセスしたいときはいつでも、最初に新しいトップリストエンティティを作成する必要があるかどうかを確認します(新しい週)。

2)質問は次のとおりです。

それは可能ですか?

  • ユーザーAは月曜日の00:00:01にmydomain.com/toplistにアクセスします->コードは新しいエンティティを生成する必要があります
  • サーバーの速度が低下し、コードの実行に3秒かかります
  • したがって、新しいトップリストエンティティは月曜日の00:00:04にデータベースに保存されます
  • ユーザーBは、月曜日の00:00:02にmydomain.com/toplistにアクセスします。
  • 00:00:02に、トップリストはまだデータベースに保存されていないため、UserBのリクエストにより、コードがトリガーされて別のトップリストエンティティが作成されます。

そして..数秒後、今週のトップリストエンティティが2つあります。

これは可能ですか?

どうすればこれを防ぐことができますか?

4

1 に答える 1

2

はい、可能です。db値(dbに保存される値)に基づいて計算を実行するときは、ロックを使用する必要があります。

doctrineのドキュメントでロックの詳細を読む:ロックのサポート

于 2012-07-01T09:22:42.833 に答える