0

In my code to reuse the redis connection across multiple URL route, is this the correct way to define instance for a single threaded in Redis?

class Red
    @conn ||= H2O::Redis.new(:host => '127.0.0.1', :port => 6379)
    class << self
      attr_reader :conn
    end
end


e.g. Route "/set"
    require "/www/test.rb"
    redis = Red.conn
    redis.set(...)

e.g. Route "/get"
    require "/www/test.rb"
    redis = Red.conn
    redis.get(...)
James Lei
  • 340
  • 2
  • 5
  • 15
  • That will work, you can see you're using the same object each time by calling `Red.conn.object_id` – Anthony Mar 24 '18 at 19:30
  • `require Red` won't work, you need to require a file not a class and also you shouldn't require in the routes, require elsewhere – max pleaner Mar 24 '18 at 20:23
  • @max pleaner, I have edited the code, it's "/www/test.rb" working on MRuby in H2O web server. – James Lei Mar 24 '18 at 22:47
  • @Anthony There was one suggested implement using "connection pool" libraries, is my code Singleton really suitable for web server environement? – James Lei Mar 24 '18 at 22:52

1 Answers1

0

For a single threaded web server running on a single process, absolutely this is the correct way to do it. You will have no issues, as Ruby's GIL ensures no two lines of code will ever run in parallel.

The question arises when you start spawning multiple processes through forking them - as that shares the memory before its modified. And looking through documentation of some services that do forking, they do recommend you re-establish connections: https://www.phusionpassenger.com/library/indepth/ruby/spawn_methods/#am-i-responsible-for-reestablishing-database-connections-after-the-preloader-has-forked-a-child-process

Nether
  • 1,081
  • 10
  • 14