Created
          July 9, 2012 15:50 
        
      - 
      
- 
        Save ryangraham/3077274 to your computer and use it in GitHub Desktop. 
    gobbling memory with eventmachine, activerecord, and apache benchmark
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | #!/usr/bin/env ruby | |
| require 'sinatra/async' | |
| require 'logger' | |
| require 'em-synchrony' | |
| require 'em-synchrony/mysql2' | |
| require 'em-synchrony/activerecord' | |
| $logger = Logger.new(File.join(File.dirname(__FILE__), "error.log")) | |
| ActiveRecord::Base.logger = Logger.new(File.join(File.dirname(__FILE__), "active_record.log")) | |
| # I made the table like this: | |
| # create table logged_events (ip varchar(255),param2 varchar(255),param3 varchar(255),param4 varchar(255),param5 varchar(255),date datetime); | |
| class LoggedEvent < ActiveRecord::Base | |
| attr_accessible :ip, :param2, :param3, :param4, :param5, :date | |
| validates :ip, :presence => true | |
| validates :param2, :presence => true | |
| validates :param3, :presence => true | |
| validates :param4, :presence => true | |
| validates :param5, :presence => true | |
| validates :date, :presence => true | |
| end | |
| class LoggerDaemon < Sinatra::Base | |
| set :server, :thin | |
| set :port, 3000 | |
| register Sinatra::Async | |
| ActiveRecord::Base.establish_connection( | |
| :adapter => 'em_mysql2', | |
| :database => 'asdf', | |
| :username => 'asdf', | |
| :password => 'asdf', | |
| :host => 'asdf', | |
| :pool => 8 | |
| ) | |
| aget '/event/' do | |
| body "ack" | |
| ip = request.ip # TODO: use X-Forwarded-For to avoid getting netscaler IP | |
| param2 = params["param2"] | |
| param3 = params["param3"] | |
| param4 = params["param4"] | |
| param5 = params["param5"] | |
| date = Time.now | |
| # Kick start ruby's garbage collector every x seconds | |
| # This is a bad idea hth | |
| EM.add_periodic_timer(5) do | |
| GC.start | |
| $logger.info "Called GC.start" | |
| end | |
| EM.next_tick do | |
| Fiber.new { | |
| LoggedEvent.create(:ip => ip, :param2 => param2, :param3 => param3, :param4 => param4, :param5 => param5,:date => date) | |
| }.resume | |
| end | |
| end | |
| # netscaler presence monitor | |
| aget '/monitor/' do | |
| body 'ack' | |
| end | |
| run! if app_file == $0 | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment