API REST调用-极大地损害了速度

问题描述 投票:0回答:1

希望有一个好人能为您提供帮助。我接到了REST api的电话-我的网上商店有更新的价格和库存。目前,它每小时调用一次,但是由于有10.000个产品,因此在6个循环中进行api调用。

问题是,api提供程序-不接受每天有144个循环/正在运行。所以他们要求我改变这一点。我不确定是否会做得更好,并且可能每天可能运行3次上午06点十二点05 pm

或者是否有可能对调用进行更好的定义,因此它不会每小时运行6个循环,但重要的是插件/ API不会破坏网络速度。

这里是代码,我曾经使用过:

add_action('wp', 'set_services_listings_cron');

function set_services_listings_cron()
{
    if (!wp_next_scheduled('set_services_listings_cron_act1')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act1');
    }
    if (!wp_next_scheduled('set_services_listings_cron_act2')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act2');
    }
    if (!wp_next_scheduled('set_services_listings_cron_act3')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act3');
    }
    if (!wp_next_scheduled('set_services_listings_cron_act4')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act4');
    }
    if (!wp_next_scheduled('set_services_listings_cron_act5')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act5');
    }
    if (!wp_next_scheduled('set_services_listings_cron_act6')) {
        wp_schedule_event(time(), 'hourly', 'set_services_listings_cron_act6');
    }

}
add_action('set_services_listings_cron_act1', 'updateData1');
add_action('set_services_listings_cron_act2', 'updateData2');
add_action('set_services_listings_cron_act3', 'updateData3');
add_action('set_services_listings_cron_act4', 'updateData4');
add_action('set_services_listings_cron_act5', 'updateData5');
add_action('set_services_listings_cron_act6', 'set_status');



function getStockFile()
{
    $datestring = date(DateTime::ISO8601);
//    $username = xx
    $username = 'xx
    $nounce = rand(); //"12121212241";
//    $generated_password = 
    $generated_password = 

    $soaprequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>
                    <soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:bf=\"xxxx"><soap:Header>
                        <bf:AuthHeader> AuthHeader
                            <bf:Username>" . $username . "</bf:Username>
                            <bf:Nonce>" . $nounce . "</bf:Nonce>
                            <bf:Created>" . $datestring . "</bf:Created>
                            <bf:Password>" . $generated_password . "</bf:Password>
                        </bf:AuthHeader>
                    </soap:Header>
                    <soap:Body>
                        <bf:GetStockFileRequest> GetStockFileRequestType
                            <bf:TestMode>false</bf:TestMode>
                            <bf:StockFileFormat>JSON</bf:StockFileFormat>
                            <bf:SortBy>FullName</bf:SortBy>
                            <bf:StockFileFields> ArrayOfStockFileField
                               <bf:StockFileField>FullName</bf:StockFileField>
                               <bf:StockFileField>Barcode</bf:StockFileField>
                               <bf:StockFileField>Brand</bf:StockFileField>
                               <bf:StockFileField>BreakBulkReference</bf:StockFileField>
                               <bf:StockFileField>Category</bf:StockFileField>
                               <bf:StockFileField>Collection</bf:StockFileField>
                               <bf:StockFileField>Category</bf:StockFileField>
                               <bf:StockFileField>Collection</bf:StockFileField>
                               <bf:StockFileField>Description</bf:StockFileField>
                               <bf:StockFileField>Gender</bf:StockFileField>
                               <bf:StockFileField>HighResImageUrl</bf:StockFileField>
                               <bf:StockFileField>Price</bf:StockFileField>
                               <bf:StockFileField>Quantity</bf:StockFileField>
                               <bf:StockFileField>Size</bf:StockFileField>
                               <bf:StockFileField>StockCode</bf:StockFileField>
                               <bf:StockFileField>StockLevel</bf:StockFileField>
                               <bf:StockFileField>ThumbnailImageUrl</bf:StockFileField>
                               <bf:StockFileField>Type</bf:StockFileField>
                            </bf:StockFileFields>
                        </bf:GetStockFileRequest>
                    </soap:Body></soap:Envelope>";

    $header = array(
        "Content-type: application/json ;charset=utf8",
        "Accept: text/xml",
//        "Cache-Control: no-cache",
//        "Pragma: no-cache",
//        "SOAPAction: \"run\"",
//        "Content-length: ".strlen($soap_request),
    );

    $soap_do = curl_init();
    curl_setopt($soap_do, CURLOPT_URL, "http://www.xxxx");
    curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($soap_do, CURLOPT_POST, true);
    curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soaprequest);
    curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);

    $html = (curl_exec($soap_do));
		//var_dump($html);

    $stockfileArray = null;
    if ($html === false) {
        $err = 'Curl error: ' . curl_error($soap_do);
        curl_close($soap_do);
        print $err;
    } else {
        curl_close($soap_do);
        $xmlfile = htmlentities($html);


        $search = array('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"', '<soapenv:Header/', '<soapenv:Body', '</', '<');
        $replace = array(' ', ' ', ' ', '@end@', '*start*');
        $customer = str_replace($search, $replace, $html);
        $soapres = explode('*start*', $customer);

        foreach ($soapres as $key => $value) {
            $res[$key] = $value;
            $temp = explode('@end@', $value);
            $tempval = explode('>', $temp[0]);
            $tmp = explode("State", $tempval[0]);
            $resp{$tempval[0]} = $tempval[1];
        }

        $stockfileArray = json_decode(base64_decode($resp['ns1:File']));
        return $stockfileArray;
    }


}

if(isset( $_GET['xxxx'] ) ){
	//add_action('init','start_import');
}

function set_status(){
  $stock_file = getStockFile();
  $sku_arr = array();
  for( $i = 0; $i< 10000;$i++ ){
		$sku = $stock_file[$i]->StockCode;
    if( !empty( $sku )){
      $sku_arr[] = $sku;
    }
	}

  $out_of_stock_staus = 'outofstock';
  $products = get_all_products_sku();
  foreach( $products as $key => $pr ){
    if( !in_array( $pr, $sku_arr) ){

      if( $key  == 64612 ){
        continue;
      }
        update_post_meta( $key, '_stock_status', wc_clean( $out_of_stock_staus ) );
        wp_set_post_terms( $key, 'outofstock', 'product_visibility', true );
        update_post_meta($key, '_stock', 0);
    }
  }
}
function updateData1()
{
    update_products_api(getStockFile(), 0, 2000);
}
function updateData2()
{
    update_products_api(getStockFile(), 2000, 4000);
}
function updateData3()
{
    update_products_api(getStockFile(), 4000, 6000);
}
function updateData4()
{
    update_products_api(getStockFile(), 6000, 8000);
}
function updateData5()
{
    update_products_api(getStockFile(), 8000, 10000);
}
function update_products_api($stockfileArray,$start,$end){


  for( $i =$start; $i< $end; $i++ ){
      $sku = $stockfileArray[$i]->StockCode;

      $products_ids = get_all_products_ids($sku);

      foreach( $products_ids  as $pid ){
					update_post_meta($pid, '_stock', $stockfileArray[$i]->StockLevel );
					update_post_meta($pid, '_regular_price', $stockfileArray[$i]->Price);
          update_post_meta($pid, '_price', $stockfileArray[$i]->Price);
          update_post_meta($pid, '_manage_stock', '1');
          update_post_meta($pid, '_stock_status', ' ' );
          wp_set_post_terms($pid, 'outofstock', ' ', true );
          $out_of_stock_staus = 'outofstock';
          if( empty($stockfileArray[$i]->StockLevel) || $stockfileArray[$i]->StockLevel < 1 ){
            update_post_meta( $pid, '_stock_status', wc_clean( $out_of_stock_staus ) );
          }

				}

    }
}

function getArrayOfPostSku()
{
	$args = array(
			'post_type' => 'product_variation',
			'posts_per_page' => -1,
			'paged' => 0,
			'post_status' => 'any',//array('publish','draft'),
	);
	$listOfPosts = get_posts($args);
    //$listOfPosts = getAllPost();//get_posts(array('post_type' => 'product', 'post_status' => 'draft', 'posts_per_page' => 6000));
    $stockCodes = array();
    foreach ($listOfPosts as $post) {
//echo $post->ID.' AN SKU ';       echo '<pre>',print_r(get_post_meta($post->ID, '_sku', true)),'<pre>';
      //  $stockCodes[get_post_meta($post->ID, '_sku', true)] = $post->ID;
    }
		die;
		//echo '<pre>',print_r( $stockCodes),'</pre>';
    return $stockCodes;
}

// if( $_GET['test'] ){
// 	add_action('init','test_fun');
// }
// function test_fun(){
// 	var_dump(get_all_products_ids('L03050'));
// }

function get_all_products_sku(){
  $args = array(
			'post_type' => 'product_variation',
			'posts_per_page' => -1,
			'paged' => 0,

			'post_status' => 'any',//array('publish','draft'),
	);
	$products = array();
	$listOfPosts = get_posts($args);
	if( !empty( $listOfPosts) ){
		foreach( $listOfPosts as $pod){
			$products[$pod->ID] =  get_post_meta($pod->ID, '_sku',true);
		}
	//	return $products;
	}

  $args1 = array(
			'post_type' => 'product',
			'posts_per_page' => -1,
			'paged' => 0,
			'post_status' => 'any',//array('publish','draft'),
	);
	$listOfPosts = get_posts($args1);
	if( !empty( $listOfPosts) ){
		foreach( $listOfPosts as $pod){
			$products[$pod->ID] = get_post_meta($pod->ID, '_sku',true);
		}
	//	return $products;
	}
  return $products;

}

function get_all_products_ids($sku){
	$args = array(
			'post_type' => 'product_variation',
			'posts_per_page' => -1,
			'paged' => 0,
			'meta_query'=> array(
				array(
					'key'=> '_sku',
					'value' => $sku,
				)
			),
			'post_status' => 'any',//array('publish','draft'),
	);
	$products = array();
	$listOfPosts = get_posts($args);
	if( !empty( $listOfPosts) ){
		foreach( $listOfPosts as $pod){
			$products[] = $pod->ID;
		}
	//	return $products;
	}

	$args1 = array(
			'post_type' => 'product',
			'posts_per_page' => -1,
			'paged' => 0,
			'meta_query'=> array(
				array(
					'key'=> '_sku',
					'value' => $sku,
				)
			),
			'post_status' => 'any',//array('publish','draft'),
	);
	$listOfPosts = get_posts($args1);
	if( !empty( $listOfPosts) ){
		foreach( $listOfPosts as $pod){
			$products[] = $pod->ID;
		}
	//	return $products;
	}

	if( !empty( $products ) ){
		return $products;
	}
	return null;
}

希望有人可以帮助我-这是一个大问题。问候基督教

php api plsqldeveloper
1个回答
0
投票

根据我的理解,这是我的建议:跟踪那些更改了数量或价格的产品(或数据库中的记录)。然后进行API调用,仅更新这些已更改的产品!这样,您不必通过其API将所有产品详细信息发送给服务提供商。

例如,如果您有1000种产品,而只有250种产品的价格/库存有变化,那么您只需要将这250种产品更新给服务提供商即可。不必更新所有1000种产品!因为750个产品没有更改。


我注意到的另一件事是,您似乎正在使用WordPress的日程安排。为什么不创建一个单独的PHP页面并使用CRON作业安排API调用。这样,您可能不必加载所有不需要的WordPress内容,并且可以节省一些服务器资源(如果这是您主要关心的问题)。只需增加此PHP脚本的最大执行时间即可(假设可能需要一些时间才能一次性提取所有这些数据),并通过一个API调用将其发送给您的服务提供商!

© www.soinside.com 2019 - 2024. All rights reserved.