【问题标题】:Silverstripe - Restful Server CachingSilverstripe - Restful 服务器缓存
【发布时间】:2013-07-01 11:59:21
【问题描述】:

对于 Web 应用程序(图像数据库),我使用的是 Restful 服务器模块。数据由另一个 Web 应用程序(商店)请求。 XML 的生成最多需要 1 秒。商店必须等待 API 响应才能显示例如产品页面。是否可以为 Restful Server API 激活一些缓存?

我已经尝试过Static Publisher,但它似乎只适用于 cms 页面。 非常感谢, 弗洛里安

【问题讨论】:

  • 我还没有听说过解决方案...但是根据需要花费这么多时间的原因,AJAX 查询可以在客户端缓存,或者如果它是服务器本身,则可以将 XML 结果保存为服务器上以查询哈希作为名称的文件?

标签: rest caching content-management-system silverstripe


【解决方案1】:

RestfulService 为您进行缓存。它接受 2 个参数。一个 serviceURL 和一个缓存时间。默认值为 3600(1 小时)。这只有在商店是用银条建造时才有效。

$serviceURL = 'http://www.imagedatabase.com/api/v1/Product?ID=1';
$service = new RestfulService($serviceURL, 7200); //2 hours expiry

$xml = $service->request()->getBody();

//get fields values
$productName = $service->searchValue($xml, 'Name');
$productPrice = $service->searchValue($xml, 'Price');

假设 Product 是一个数据对象,您还需要对 Product 进行修改。

class Product extends DataObject {
    ...
    static $api_access = true;
    ...
    function canView($member = null) {
        return true;
    }

}

RestfulService 文档 http://doc.silverstripe.org/framework/en/reference/restfulservice

【讨论】:

    【解决方案2】:

    好吧,我个人会缓存在客户端(所以在商店里)

    但如果你必须这样做,我认为没有任何内置方法可以做到这一点。 你可以子类化 restful 服务器并自己做一些基本的缓存(就像默认的 SS RestfulClient 那样,将它保存到一个文件中)

        class MyServer extends RestfulServer {
        public $cache_expire;
    
        function __construct($cache_expire = 3600) {
            $this->cache_expire = $cache_expire;
        }
    
        protected function getHandler($className, $id, $relationName) {
            $cache_path = Director::getAbsFile("assets/rest-cache/$className-$id-$relationName.{$this->request->getExtension()}");
            if ($this->cache_expire > 0 && !isset($_GET['flush'])
                && @file_exists($cache_path) && @filemtime($cache_path) + $this->cache_expire > time()
            ) {
                $store = file_get_contents($cache_path);
                $response = unserialize($store);
            } else {
                $response = parent::getHandler($className, $id, $relationName);
                $store = serialize($response);
                file_put_contents($cache_path, $store);
            }
            return $response;
        }
    }
    

    // 注意,我从未测试过这段代码,所以你可能会遇到一些小的拼写错误或类似的问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-07
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多