我尝试设置自动压力测试,并将随机生成的数据提供给Redis,然后让消费者(作为另一个从Redis读取的组件)处理随机数据。
为了模拟随机生成的数据接近真实世界的时间,我决定放入一个无限循环,并使用EventMachine来处理同步。我不确定我在使用EventMachine做了什么,但我听说它会比继续产生新线程并阻止主进程更好。我这样做了吗?
EventMachine.synchrony do
@redis = EM::Hiredis.connect
# hit Control + C to stop
Signal.trap("INT") { EventMachine.stop }
Signal.trap("TERM") { EventMachine.stop }
trip_id = 0
loop do
longitude, latitude = [0.0, 0.0]
for i in 0..100
# now loop
longitude, latitude = random_coordinates
sleep 0.05 # sleep a bit to simulate the real world
end
puts "this trip #{trip_id} | #{longitude} : #{latitude}"
trip_id += 1
redis.set('trip_id', trip_id)
end
end
已编辑1
所以我最终用线程池
来做require "thread/pool"
require "json"
require "redis"
require 'thread_safe'
def publish_on_redis(hash)
@redis ||= Redis.new
@redis.publish("trips", hash.to_json)
end
# Using thread-safe data structure
@trip_id_list = ThreadSafe::Array.new()
TRIP.times {|n| @trip_id_list[n] = n}
@trip_id_list.shuffle!
pool = Thread.pool(TRIP)
loop do
@trip_id_list.each do |trip_id|
pool.process {
longitude, latitude = [0.0, 0.0]
# Everything has to be UTC timestamp, everyone is on the same timezone
start = Time.now.utc
while((Time.now.utc - start) < @total_duration)
longitude, latitude = random_coordinates_radius
publish_on_redis({:id => trip_id, :time => Time.now, :longitude => longitude, :latitude => latitude})
sleep 1 # sleep at each run some amount of times
end
publish_on_redis({:id => trip_id, :time => Time.now, :longitude => longitude, :latitude => latitude})
@trip_id_list.delete(trip_id)
}
end
break # will have to exit the infinite loop
end
pool.shutdown
答案 0 :(得分:0)
像你在这里一样生成随机事件似乎是正确的。
但是,你根本没有强调redis,你只是做了一个简单的'set',它会用新数据覆盖密钥(如果存在的话)。
我建议使用一个管道,你填充了大量的数据,你在测试块中执行+等待(带睡眠)。
将sleep语句移出数据准备代码之外。
希望这有帮助,TW