簡體   English   中英

Wordpress REST API 緩存問題 - WP 引擎

[英]Wordpress REST API Caching Issue - WP Engine

我創建了一個自定義插件,它實際上只注冊了幾個 API 端點。

現在我遇到的問題是所有端點都在本地正常工作,但是當我將此代碼推送到我托管我的 WordPress 站點的 WpEngine 時,API 響應正在被緩存。

如果我通過 WPEngine 清除緩存並再次發出請求,API 工作正常,直到第一次收到 200 成功響應,一旦收到成功,那么無論 header 是什么,端點總是返回相同的響應,我給那個端點的參數值。

在 wp-config.php 文件中我禁用了緩存 - define( 'WP_CACHE', false );

也嘗試添加

wp_cache_flush(); nocache_headers();

在請求操作回調函數中,仍然沒有成功,總是緩存響應。

幾個代碼片段供您參考 -

// This is the route I've registered

public function register_routes()
{
   register_rest_route($namespace, '/config' ,[
                'methods' => 'GET',
                'callback' => array($this, 'Action_GetConfig'),
                'permission_callback' => 'authCheck'
            ]);
}

add_action( 'rest_api_init', array( $this, 'register_routes' ) );


        function Action_GetConfig(WP_REST_Request $request)
        {
            try {
                // wp_cache_flush();
                // nocache_headers();
  
                    $headers = $request->get_headers();

                    // Basic Validation
                    if (IsNullOrEmptyString($headers['platform'][0]) or IsNullOrEmptyString($headers['version'][0])) {
                        $resp = new WP_HTTP_Response();
                        // $resp->set_headers( array('Cache-Control' => 'no-cache, must-revalidate, max-age=0'));
                        $resp->set_status(400);
                        return $resp;
                    }
        
                    // Service Invocation
                    $results = $this->getConfig($headers['platform'][0], $headers['version'][0]);
                    $resp = new WP_HTTP_Response($results);
                    $resp->set_status(200);
                    return $resp;

            } catch (Throwable $e) {
                //$log->error($e);
                $resp = new WP_HTTP_Response($e);
                $resp->set_status(500);
                return $resp;
            }
        }

有人可以幫助解決這個 API 響應緩存問題嗎? 謝謝!

相信WP ENGINE USES,WP Engine MU PLUGIN。 如果使用此插件,您將可以訪問一些名為wpecommon::purge_varnish_cache()的函數,如果您傳遞目標帖子的 ID,則此 function 將清除帖子緩存。 但是如果你使用 function 而不傳遞 ID 那么它將清除整個域的所有緩存(我當然不推薦這種方式,因為它會導致大型網站的性能問題)。

function your_call_of_action(WP_REST_Request $request){
 $id = $request->get_param( 'id' );
 if ( FALSE === get_post_status( $id ) ) {
   $resp = new WP_HTTP_Response([]);
   $resp->set_status(500);
   return $resp;
 }
 
 wpecommon::purge_varnish_cache( $id )

// rest of your code goes here
 
}

也可以撥打以下API清除緩存:

/installs/{install_id}/purge_cache

閱讀以下文檔:

閱讀本文檔: https://wpengine.com/support/cache/
API 文檔: https://wpengineapi.com/reference

我通過在 WPEngine 中添加緩存排除策略解決了這個問題。 因為默認情況下在 WPEngine 中所有端點響應都被緩存。 因此,如果我們不想緩存特定路由,則必須將該路由添加到排除列表中。

path: ^/wp-json/nx/services/?

我在 WPEngine 的 Route RegEx 上面添加了這個。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM