我有一个存储在数据库中的300条新闻文章的RSS源列表,每隔几分钟我就抓住每一个源的内容。每个Feed包含大约10篇文章,我想将每篇文章存储在数据库中。
问题:我的数据库表超过50,000行并且快速增长;每次我运行我的脚本来获取新的feed时,它都会添加至少100行。这就是我的数据库达到100%CPU利用率的程度。
问题:如何优化我的代码/数据库?
注意:我不关心服务器的CPU(运行时为<15%)。我非常关心我的DB的CPU。
我看到的可能的解决方案:
这就是我正在做的事情:
//$this->set_content_source_cache goes through all 50,000 rows and adds each link to an array so that it's array('link', 'link', 'link', etc.)
$cache_source_array = $this->set_content_source_cache();
$qry = "select source, source_id, source_name, geography_id, industry_id from content_source";
foreach($this->sql->result($qry) as $row_source) {
$feed = simplexml_load_file($row_source['source']);
if(!empty($feed)) {
for ($i=0; $i < 10 ; $i++) {
// most often there are only 10 feeds per rss. Since we check every 2 minutes, if there are
// a few more, then meh, we probably got it last time around
if(!empty($feed->channel->item[$i])) {
// make sure that the item is not blank
$title = $feed->channel->item[$i]->title;
$content = $feed->channel->item[$i]->description;
$link = $feed->channel->item[$i]->link;
$pubdate = $feed->channel->item[$i]->pubdate;
$source_id = $row_source['source_id'];
$source_name = $row_source['source_name'];
$geography_id = $row_source['geography_id'];
$industry_id = $row_source['industry_id'];
// random stuff in here to each link / article to make it data-worthy
if(!isset($cache_source_array[$link])) {
// start the transaction
$this->db->trans_start();
$qry = "insert into content (headline, content, link, article_date, status, source_id, source_name, ".
"industry_id, geography_id) VALUES ".
"(?, ?, ?, ?, 2, ?, ?, ?, ?)";
$this->db->query($qry, array($title, $content, $link, $pubdate, $source_id, $source_name, $industry_id, $geography_id));
// this is my framework's version of mysqli_insert_id()
$content_id = $this->db->insert_id();
$qry = "insert into content_ratings (content_id, comment_count, company_count, contact_count, report_count, read_count) VALUES ".
"($content_id, '0', '0', 0, '0', '0')";
$result2 = $this->db->query($qry);
$this->db->trans_complete();
if($this->db->trans_status() == TRUE) {
$cache_source_array[$link] = $content_id;
echo "Good!<br />";
} else {
echo "Bad!<br />";
}
} else {
// link alread exists
echo "link exists!";
}
}
}
} else {
// feed is empty
}
}
}
答案 0 :(得分:1)
我想你回答了自己的问题:
目前,每次脚本运行时,都会进入 $ this-&gt; set_content_source_cache返回数组 来自表中所有行的数组('link','link','link'等)。 这用于以后的交叉引用,以确保没有 重复链接。不会这样做,只是简单地改变数据库 链接列是独特的速度吗?
是的,创建主键或唯一索引并允许数据库在出现重复时抛出错误是一种更好的做法,应该更有效率。
参考编辑: