ctp*_*ctp 6 ruby asynchronous file cassandra eventmachine
我正在玩Ruby EventMachines已有一段时间了,我想我理解它的基础知识.
但是,我不确定如何在大文件(120 MB)中进行性能读取.我的目标是逐行读取文件并将每一行写入Cassandra数据库(同样应该使用MySQL,PostgreSQL,MongoDB等,因为Cassandra客户端显式支持EM).简单的片段阻挡了反应堆,对吗?
require 'rubygems'
require 'cassandra'
require 'thrift_client/event_machine'
EM.run do
Fiber.new do
rm = Cassandra.new('RankMetrics', "127.0.0.1:9160", :transport => Thrift::EventMachineTransport, :transport_wrapper => nil)
rm.clear_keyspace!
begin
file = File.new("us_100000.txt", "r")
while (line = file.gets)
rm.insert(:Domains, "#{line.downcase}", {'domain' => "#{line}"})
end
file.close
rescue => err
puts "Exception: #{err}"
err
end
EM.stop
end.resume
end
Run Code Online (Sandbox Code Playgroud)
但是什么是异步读取文件的正确方法?
在EventMachine中没有异步文件IO支持,实现你想要做的事情的最好方法是在每个tick上读取几行并将它们发送到数据库.最重要的是不要读太大的块,因为这会阻塞反应堆.
EM.run do
io = File.open('path/to/file')
read_chunk = proc do
lines_sent = 10
10.times do
if line = io.gets
send_to_db(line) do
# when the DB call is done
lines_sent -= 1
EM.next_tick(read_chunk) if lines_sent == 0
end
else
EM.stop
end
end
end
EM.next_tick(read_chunk)
end
Run Code Online (Sandbox Code Playgroud)
请参阅基于EventMachine的应用程序中读取文件的最佳方法是什么?
| 归档时间: |
|
| 查看次数: |
2311 次 |
| 最近记录: |