[从入门到脱鞋] hello EventMachine

Hooopo 2010-08-13
eventmachine代替crontab:
#!/usr/bin/env ruby
require 'rubygems'
require 'eventmachine'
EM.run do
  EM::PeriodicTimer.new(1) do
    puts Time.now
  end
end



处理http streaming:

require 'eventmachine'
require 'em-http'
require 'json'

usage = "#{$0} <user> <password>"
abort usage unless user = ARGV.shift
abort usage unless password = ARGV.shift

url = 'http://stream.twitter.com/1/statuses/sample.json'

def handle_tweet(tweet)
  return unless tweet['text']
  puts "#{tweet['user']['screen_name']}: #{tweet['text']}"
end

EventMachine.run do
  http = EventMachine::HttpRequest.new(url).get :head => { 'Authorization' => [ user, password ] }

  buffer = ""

  http.stream do |chunk|
    buffer += chunk
    while line = buffer.slice!(/.+\r?\n/)
      handle_tweet JSON.parse(line)
    end
  end
end


event memcache client:
#!/usr/bin/env ruby
require 'rubygems'
require 'eventmachine'

EM.run{
    cache = EM::P::Memcache.connect '192.168.1.235', 11211
    p "#{Time.now.to_f} 1"
    cache.get(:ox) do |ox|
      p "#{Time.now.to_f} 2"
      p "#{ox} 3"
      p "#{Time.now.to_f} 4"
    end
    p "#{Time.now.to_f} 5"
  }
输出:

"1282635250.94503 1"
"1282635250.94514 5"
"1282635250.94594 2"
" 3"
"1282635250.94596 4"




其他待续...

links:
http://wiki.github.com/eventmachine/eventmachine/tutorials
http://www.neeraj.name/2009/12/15/ruby-eventmachine-a-short-introduction.html
Hooopo 2010-09-07
http://www.iteye.com/topic/757760
Global site tag (gtag.js) - Google Analytics