Gracefully unsubscribe from redis at exit

732 views Asked by At

I have a ruby program which listens to a redis channel:

module Listener
  class << self
    def listen
      redis.subscribe "messaging" do |on|
        on.message do |_, msg|
          Notify.about(msg)
        end
      end
    end

    def redis
      @redis ||= Redis.new(driver: :hiredis)
    end
  end
end

Every time I deploy the app I restart the process with

kill -15 listener-pid

But Airbrake notifies me about the SignalException: SIGTERM with the following backtrace

/gems/hiredis-0.6.1/lib/hiredis/ext/connection.rb:19 in read
/gems/hiredis-0.6.1/lib/hiredis/ext/connection.rb:19 in read
/gems/redis-3.3.3/lib/redis/connection/hiredis.rb:54 in read
/gems/redis-3.3.3/lib/redis/client.rb:262 in block in read
/gems/redis-3.3.3/lib/redis/client.rb:250 in io
/gems/redis-3.3.3/lib/redis/client.rb:261 in read
/gems/redis-3.3.3/lib/redis/client.rb:136 in block (3 levels) in call_loop
/gems/redis-3.3.3/lib/redis/client.rb:135 in loop
/gems/redis-3.3.3/lib/redis/client.rb:135 in block (2 levels) in call_loop
/gems/redis-3.3.3/lib/redis/client.rb:231 in block (2 levels) in process
/gems/redis-3.3.3/lib/redis/client.rb:367 in ensure_connected
/gems/redis-3.3.3/lib/redis/client.rb:221 in block in process
/gems/redis-3.3.3/lib/redis/client.rb:306 in logging
/gems/redis-3.3.3/lib/redis/client.rb:220 in process
/gems/redis-3.3.3/lib/redis/client.rb:134 in block in call_loop
/gems/redis-3.3.3/lib/redis/client.rb:280 in with_socket_timeout
/gems/redis-3.3.3/lib/redis/client.rb:133 in call_loop
/gems/redis-3.3.3/lib/redis/subscribe.rb:43 in subscription
/gems/redis-3.3.3/lib/redis/subscribe.rb:12 in subscribe
/gems/redis-3.3.3/lib/redis.rb:2765 in _subscription
/gems/redis-3.3.3/lib/redis.rb:2143 in block in subscribe
/gems/redis-3.3.3/lib/redis.rb:58 in block in synchronize
/usr/lib/ruby/2.4.0/monitor.rb:214 in mon_synchronize
/gems/redis-3.3.3/lib/redis.rb:58 in synchronize
/gems/redis-3.3.3/lib/redis.rb:2142 in subscribe

Is it possible to restart the listener process gracefully so I wont receive SIGTERM errors?

1

There are 1 answers

0
Hirurg103 On BEST ANSWER

I found a pubsub example in redis-rb

After I added trap('SIGTERM') { exit } the problem was fixed

Now my listener class looks like this:

module Listener
  class << self
    def listen
      trap('SIGTERM') { exit }

      redis.subscribe "messaging" do |on|
        on.message do |_, msg|
          Notify.about(msg)
        end
      end
    end

    def redis
      @redis ||= Redis.new(driver: :hiredis)
    end
  end
end