如何更快地获取HttpWebResponse返回信息的内容
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何更快地获取HttpWebResponse返回信息的内容相关的知识,希望对你有一定的参考价值。
参考技术A // Create a 'WebRequest' object with the specified url.WebRequest myWebRequest = WebRequest.Create();
// Send the 'WebRequest' and wait for response.
WebResponse myWebResponse = myWebRequest.GetResponse();
// Obtain a 'Stream' object associated with the response object.
Stream ReceiveStream = myWebResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
// Pipe the stream to a higher level stream reader with the required encoding format.
StreamReader readStream = new StreamReader( ReceiveStream, encode );
Console.WriteLine("\nResponse stream received");
Char[] read = new Char[256];
// Read 256 charcters at a time.
int count = readStream.Read( read, 0, 256 );
Console.WriteLine("HTML...\r\n");
while (count > 0)
// Dump the 256 characters on a string and display the string onto the console.
String str = new String(read, 0, count);
Console.Write(str);
count = readStream.Read(read, 0, 256);
Console.WriteLine("");
// Release the resources of stream object.
readStream.Close();
// Release the resources of response object.
myWebResponse.Close();
如何优化限制查询以更快地从大表中访问数据?
【中文标题】如何优化限制查询以更快地从大表中访问数据?【英文标题】:How to optimize limit query to access data faster from a huge table? 【发布时间】:2019-04-15 08:03:13 【问题描述】:我正在尝试从大小为 9 GB + 并拥有数百万条记录的表中获取数据。我正在用该数据填充 DataTable。我通过 Ajax 和 SQL 限制查询从表中获取记录,即每页 10 条。
pagination
在上图中,您可以看到我们有223,740
页面,因此当我尝试访问最后一页时,查询需要永远加载数据。但是,当我尝试访问首页时,数据加载速度更快。但是直接访问更高偏移量的页面需要永远加载。
public static function getAllEvaluationsWithNameForDataTable($start)
$queryBuilder = new Builder();
return $queryBuilder
->from(array('e' => static::class))
->leftJoin('Cx\Framework\Models\Common\User\CxUser', 'e.cx_hc_user_id = u.id', 'u')
->columns('e.id, e.first_name, u.initials as assigned_coach, e.gender, e.email, e.phone, e.age, e.version, e.evaluation_status, e.ip_address, e.date_created, e.date_updated')
->orderBy('e.id asc')
->limit(10, $start)
->getQuery()
->execute()
->toArray();
PHP 函数/控制器:
public function getEvaluationsAction()
// Enable Json response
$this->setJsonResponse();
// This action can be called only via ajax
$this->requireAjax();
// Forward to access denied if current user is not allowed to view evaluation details
if (!$this->CxAuth->currentUserIsAllowedTo('VIEW', CxEbEvaluation::getClassResourceName()))
return $this->forwardToAccessDeniedError();
if(isset($_GET['start']))
$start = $this->request->get('start');
else
$start = 10;
$recordsTotal = count(CxEbEvaluation::getAllForDataTable(array('id')));
//Get Evaluations from DB
$evaluation_quizzes = CxEbEvaluation::getAllEvaluationsWithNameForDataTable(intval($start));
//for getting base URL
$url = new Url();
$data = array();
foreach ($evaluation_quizzes as $key => $quiz)
$data[ $key ][ 'id' ] = $quiz[ 'id' ];
$data[ $key ][ 'first_name' ] = $quiz[ 'first_name' ];
if($quiz[ 'assigned_coach' ])
$data[ $key ][ 'assigned_coach' ] = $quiz['assigned_coach'];
else
$data[ $key ][ 'assigned_coach' ] = "Not assigned";
$data[ $key ][ 'gender' ] = $quiz[ 'gender' ];
$data[ $key ][ 'email' ] = $quiz[ 'email' ];
$data[ $key ][ 'phone' ] = $quiz[ 'phone' ];
$data[ $key ][ 'age' ] = $quiz[ 'age' ];
$data[ $key ][ 'version' ] = $quiz[ 'version' ];
$data[ $key ][ 'quiz' ] = $url->get('/admin/get-evaluation-quiz-by-id');
$data[ $key ][ 'manage-notes-messages-and-calls' ] = $url->get('/admin/manage-notes-messages-and-calls');
$data[ $key ][ 'date_created' ] = date("m/d/Y H:i:s", $quiz[ 'date_created' ]);
$data[ $key ][ 'evaluation_status' ] = $quiz[ 'evaluation_status' ];
// Return data array
return array(
"recordsTotal" => $recordsTotal,
"recordsFiltered" => $recordsTotal ,
"data" => $data //How To Retrieve This Data
);
// Return data
Javascript:
cx.common.data.cxAdminDataTables.EbEvaluation = $CxRecordsTable.cxAdminDataTable(
ajaxUrl: '<?php echo $this->CxHelper->Route('eb-admin-get-evaluations')?>' + eqQuizIdQueryString,
serverSide: true,
processing: true,
recordsFiltered :true,
columns: [
cx.common.admin.tableEditColumn('id', delete: true ),
data: 'first_name' ,
data: 'assigned_coach' ,
data: 'gender' ,
data: 'email' ,
data: 'phone' ,
data: 'age' ,
cx.common.admin.tableLinkColumn('quiz', quizLinkOptions),
cx.common.admin.tableEditColumn('id', healthCoachLinkOptions),
cx.common.admin.tableLinkColumn('manage-notes-messages-and-calls', manageNotesMessagesAndCalls),
data: 'date_created' ,
cx.common.admin.tableSwitchableColumn('evaluation_status',
editable: true,
createdCell: function (td, cellData, rowData, row, col)
$(td).data('evaluation-status-id', rowData.id);
,
onText: 'Complete',
offText: 'In progress'
)
],
toolbarOptions:
enabled: false
, success: function (data)
cx.common.data.cxAdminDataTables.EbEvaluation.cxAdminDataTable("reloadAjax");
);
else
$row.removeClass('alert');
);
);
我希望问题很清楚。如果需要其他任何内容,请更新我,我会提供。
(来自评论)
SELECT e.id` AS id, e.first_name AS first_name,
u.initials AS assigned_coach,
e.gender AS gender, e.email AS email, e.phone AS phone,
e.age AS age, e.version AS version,
e.evaluation_status AS evaluation_status,
e.ip_address AS ip_address, e.date_created AS date_created,
e.date_updated AS date_updated
FROM evaluation_client AS e
LEFT JOIN cx_user AS u ON e.cx_hc_user_id = u.id
ORDER BY e.id ASC
LIMIT :APL0 OFFSET, :APL1
【问题讨论】:
dba.stackexchange.com/questions/66294/… dba.stackexchange.com/questions/75963/… ***.com/questions/4481388/… 你需要一个索引。 @MasivuyeCokile 尝试了上面的 *** 链接,但它与我的场景无关。 【参考方案1】:模式SELECT whatever FROM vast_table ORDER BY something LIMIT 10 large_number
是一个臭名昭著的性能反模式。为什么?因为它必须检查很多行才能返回一些。
如果您的 id
值是主键(或任何索引列),您可以分页
SELECT whatever FROM vast_table WHERE id BETWEEN large_value AND large_value+9 ORDER BY id;
或者你可以试试
SELECT whatever FROM vast_table WHERE id >= large_value ORDER BY id LIMIT 10;
如果您的 id
值中有空格,则这不会完美分页。但它的表现还算不错。
【讨论】:
你好@O。琼斯我已经尝试过类似的,但正如你提到的,它会跳过记录。return $queryBuilder ->from(array('e' => static::class)) ->leftJoin('Cx\Framework\Models\Common\User\CxUser', 'e.cx_hc_user_id = u.id', 'u') ->columns('e.*') ->where('e.id > :ID:') ->orderBy('e.id asc') ->limit(10, $start) ->getQuery() ->execute(array('ID' => $start)) ->toArray();
@DojoDev - 好吧,听起来 QueryBuilder 不是一个很好的工具。
您不应该在limit(10, $start)
中包含您的起点。你可能想要where('e.id >= :ID:')
注意>=
。【参考方案2】:
由 Masivuye Cokile 链接的Why does MYSQL higher LIMIT offset slow the query down? 问题和答案以及那里提供的https://explainextended.com/2009/10/23/mysql-order-by-limit-performance-late-row-lookups/ 链接,包含关于为什么大偏移量查询缓慢的优秀纲要。基本上,对于LIMIT 150000, 10
,MySQL 仍然会扫描整个 150000 行,即使它稍后会丢弃它们。要加快速度,您可以:
count
查询计算得出的大致页码。
或在id
上创建索引,然后强制mysql执行仅索引搜索。
对于第二种方法,您必须从
重写查询SELECT ...
FROM table t
WHERE ...
ORDER by t.id ASC
LIMIT 150000, 10
到
SELECT ...
FROM (
SELECT id
FROM table
ORDER BY
id ASC
LIMIT 150000, 10
) o
JOIN table t
ON t.id = o.id
WHERE ...
ORDER BY t.id ASC
或者,由于您不局限于单个查询,您可以使用
检索页面上第一个项目的 IDSELECT id
FROM table
ORDER BY id ASC
LIMIT 150000, 1
然后使用该 id 检索实际数据:
SELECT ...
FROM table
WHERE id >= $id
AND ...
ORDER BY id ASC
LIMIT 0, 10
【讨论】:
More on '记住你离开的地方'。 @Timekiller 在哪里可以找到第一项的 id?你是说数据表的 $start 变量吗? 整体第一项还是页面上的第一项?如果您的意思是整体,请使用select min(id)
或使用id >= 0
之类的东西;如果您指的是页面上的第一项,请查看我的倒数第二个查询并调整 limit 150000, 1
部分,使偏移量匹配 pages*items_per_page
而不是 150000。【参考方案3】:
问题与我表中的日期列数据类型有关。我在日期字段中使用int
数据类型,当我将日期列的数据类型更改为datetime
时,搜索结果以秒为单位。
我找到解决方案的来源@http://dbscience.blogspot.com/2008/08/can-timestamp-be-slower-than-datetime.html
【讨论】:
以上是关于如何更快地获取HttpWebResponse返回信息的内容的主要内容,如果未能解决你的问题,请参考以下文章
从 HttpWebRequest 和 HttpWebResponse 获取 Http 状态码(200、301、404 等)
如何将此方法转换为更快地使用 LockBits 并且它将比较 3 个或更多图像?
System.Net.HttpWebResponse.GetResponseStream() 在 WebException 中返回截断的正文