我正在尝试最大化每秒插入次数。我目前获得大约 20k 插入/秒。我使用的线程和 CPU 越多(我有 16 个内核可用),我的性能实际上就会下降。在 16 核双处理器机器上,目前 2 个线程每秒比 16 个线程执行更多操作。关于问题是什么的任何想法?是因为我只使用一个mongod吗?是索引可能会减慢速度吗?我需要使用分片吗?我想知道是否有办法进行分片,但还要保持数据库上限......
约束:必须处理大约 30 万次插入/秒,必须是自限制(封顶),必须能够相对快速地进行查询
问题空间:必须处理大型手机公司的通话记录(大约 30 万次插入/秒)并尽可能长时间(例如一周)使这些通话记录可查询
#!/usr/bin/perl
use strict;
use warnings;
use threads;
use threads::shared;
use MongoDB;
use Time::HiRes;
my $conn = MongoDB::Connection->new;
my $db = $conn->tutorial;
my $users = $db->users;
my $cmd = Tie::IxHash->new(
"create" => "users",
"capped" => "boolean::true",
"max" => 10000000,
);
$db->run_command($cmd);
my $idx = Tie::IxHash->new(
"background"=> "boolean::true",
);
$users->ensure_index($idx);
my $myhash =
{
"name" => "James",
"age" => 31,
# "likes" => [qw/Danielle biking food games/]
};
my $j : shared = 0;
my $numthread = 2; # how many threads to run
my @array;
for (1..100000) {
push (@array, $myhash);
$j++;
}
sub thInsert {
#my @ids = $users->batch_insert(\@array);
#$users->bulk_insert(\@array);
$users->batch_insert(\@array);
}
my @threads;
my $timestart = Time::HiRes::time();
push @threads, threads->new(\&thInsert) for 1..$numthread;
$_->join foreach @threads; # wait for all threads to finish
print (($j*$numthread) . "\n");
my $timeend = Time::HiRes::time();
print( (($j*$numthread)/($timeend - $timestart)) . "\n");
$users->drop();
$db->drop();
最佳答案
写入 MongoDB 当前需要全局写入锁,尽管 collection level locking希望很快就会到来。通过使用更多线程,您可能会引入更多并发问题,因为线程在等待释放锁时会相互阻塞。
索引也会减慢您的速度,为了获得最佳插入性能,最好在加载数据后添加它们,但这并不总是可行的,例如,如果您使用的是唯一索引。
要真正最大化写入性能,最好的选择是分片。当您在多台机器上分配写入时,这将为您提供更好的并发性和更高的磁盘 I/O 容量。
https://stackoverflow.com/questions/7265176/