如何在 ruby 中将 CustomHealthCheck 与 health_check gem 一起使用?

How to use CustomHealthCheck with health_check gem in ruby?

health_check官方网站得知,它可以在配置文件中添加一个config.add_custom_check块:

https://github.com/ianheggie/health_check

# Add one or more custom checks that return a blank string if ok, or an error message if there is an error
config.add_custom_check do
  CustomHealthCheck.perform_check # any code that returns blank on success and non blank string upon failure
end

# Add another custom check with a name, so you can call just specific custom checks. This can also be run using
# the standard 'custom' check.
# You can define multiple tests under the same name - they will be run one after the other.
config.add_custom_check('sometest') do
  CustomHealthCheck.perform_another_check # any code that returns blank on success and non blank string upon failure
end

但是关于CustomHealthCheckclass,如何定义呢?

对于okcomputergem,它提供了这样的方式:

https://github.com/sportngin/okcomputer

# config/initializers/okcomputer.rb
class MyCustomCheck < OkComputer::Check
  def check
    if rand(10).even?
      mark_message "Even is great!"
    else
      mark_failure
      mark_message "We don't like odd numbers"
    end
  end
end

OkComputer::Registry.register "check_for_odds", MyCustomCheck.new

没有找到关于health_checkgem的用法。


更新

我试过:

config/initializers/health_check.rb 文件中添加这些来源:

class CustomHealthCheck
  def perform_check
    if rand(10).even?
      p "Even is great!"
    else                                                                                                            
      p "We don't like odd numbers"
    end
  end
end

HealthCheck.setup do |config|
...

运行 curl -v localhost:3000/health_check.json, 得到:

{"healthy":false,"message":"health_check failed: undefined method `perform_check' for CustomHealthCheck:Class"}%

更新 2

config/initializers/health_check.rb 中编辑的源代码:

class CustomHealthCheck
  def self.perform_check
    p 'OK'
  end
end

HealthCheck.setup do |config|
...

得到:

{"healthy":false,"message":"health_check failed: OK"}%

返回空字符串即为成功。现在你的 perform_check 总是 returns 字符串 "OK" 这将被视为失败。

试试这个来获得通过的健康检查:

class CustomHealthCheck
  def self.perform_check
    everything_is_good = true # or call some method to do more elaborate checking
    return everything_is_good ? "" : "We've got Problems"
  end
end