0

我们为几个高负载站点提供服务,到目前为止,我们提供了用于缓存支持一些基本本地横幅旋转的远程横幅的代码。所有人都应该很容易理解,我想从您那里听到有关此代码的可能改进或建议的内容。这里是...

        $cachetime = 6 * 60 * 60; // 6 hours
        $bannercache = $_SERVER['DOCUMENT_ROOT']."/banner-".$bpos.".txt";

            // Serve from the cache if it is younger than $cachetime

            if (file_exists($bannercache) && (time() - $cachetime
             < filemtime($bannercache)))
            {

                    // if it's ok don't update from remote

            } else {

                    // if cache is old, update from remote


                    $bannercachecontent = @file_get_contents('ADSERVER.com/showad.php?category='.$adcat.'&dimensions='.$dimensions);

                    if ($bannercachecontent === FALSE) {

                        // on error, just update local time, so that it's not pulled again in case of remote mysql overload

                        $fb = @fopen($bannercache, 'a+');
                        fwrite($fb, "\n<!-- Changed date on ".date('jS F Y H:i', filemtime($cachefile))."-->\n");
                        fclose($fb);

                    } else {

                        // if it's ok, save new local file

                        $fb = @fopen($bannercache, 'w');
                        fwrite($fb, $bannercachecontent);
                        fwrite($fb, "\n<!-- Cached ".date('jS F Y H:i', filemtime($cachefile))."-->\n");
                        fclose($fb);
                    }



            }



        $fhm = file_get_contents($bannercache);



        $fhmpos = strpos($fhm, '-----#####-----'); // check if it needs to be exploded for rotation
        if ($fhmpos === false) {

            echo $fhm;

        } else {

            $fhmpicks = explode("-----#####-----", $fhm);


        foreach ($fhmpicks as $fhmkey => $fhmvalue)
        {
            if (trim($fhmpicks[$fhmkey]) == '')
            {
                unset($fhmpicks[$fhmkey]);
            }
        }


            $fhmpick = array_rand($fhmpicks,1);

            echo $fhmpicks[$fhmpick]; // show only one banner

        }
4

1 回答 1

0

Don't let your clients update your banners. You will always have 1 user that has to do this, and that isn't necessary:

Instead: let you clients always load the local image, and run a background process (cron, with a manual override if you want to pull the image NOW) that fetches the right image(s).

The code would be fairly simple:

your client does: $yourImage= $_SERVER['DOCUMENT_ROOT']."/banner-".$bpos.".txt";

and your update-script can just cURL the right image.

于 2012-08-20T11:15:49.783 回答