0

我想为 ruby​​ 应用程序设置 MySQL 数据库健康检查,基本上响应应该是

{
    "read_success": true,
    "write_success": true,
    "exception": null
}

我的健康检查应该执行以下操作:

从数据库中读取一个表 向数据库写入一些东西 如果上述任何操作失败,它应该抛出响应中提到的异常。

module API
  ApplicationName.controllers :health_check do
    get :index do
      status = {
          read_success: read_successful,
          write_success: write_successful,
          exception: check_exception
      }
       [200, {}, [status.to_json]]
    end
  end
end

def read_successful
  begin
    ActiveRecord::Base.connection.execute("SELECT 1")
    true
  rescue
    false
  end
end

def write_successful
  begin
    # logic to check write to database, which table should i write to?
    true
  rescue
    false
  end
end

def check_exception
  begin
    ActiveRecord::Base.connection.execute("SELECT 1")
    nil
  rescue Exception => e
    return e.message
  end
  begin
    # logic to check write to database, which table should i write to?
    nil
  rescue Exception => e
    return e.message
  end
end

我已经尝试像上面那样实现读取健康检查,但不知道如何实现写入健康检查?有没有什么方法可以实现写健康检查,而无需在数据库中为健康检查创建新表。

实现写入健康检查的逻辑应该是什么?

4

1 回答 1

1

最后实现它,发布答案,以便稍后帮助某人,为此,您必须在数据库中创建一个表 health_check。

CREATE TABLE `health_check` (   `id` int(11) NOT NULL AUTO_INCREMENT,   `date` varchar(40) NOT NULL,   `status` varchar(40) NOT NULL,   PRIMARY KEY (`id`) );

API

ApplicationName.controllers :deep_health_check do
  get :index do
    time_stamp = Time.now.strftime('%Y-%m-%d %H:%M:%S')
    read_error_msg = "Exception While Reading To Database: "
    write_error_msg = "Exception While Writing to Database: "
    read_success = read_successful
    write_success = write_successful(time_stamp)
    exception = nil

    str = String.new("")

    if read_success != true && write_success != true
      str = read_error_msg + read_success + "  and  " + write_error_msg + write_success
      read_success = false
      write_success = false

    elsif read_success != true && write_success == true
      str = read_error_msg + read_success
      read_success = false
    else
      if read_success == true && write_success != true
        str = write_error_msg + write_success
        write_success = false

      end
    end

    if str != ""
      exception = str
    end


    status = {
        read_success: read_success,
        write_success: write_success,
        exception: exception
    }
    [200, {}, [status.to_json]]
  end
end

def read_successful
  begin
    ActiveRecord::Base.connection.execute("SELECT 1")
    return true
  rescue Exception => e
    return e.message
  end
end

def write_successful(time_stamp)
  begin
    write_to_a_table(time_stamp)
    return true
  rescue Exception => e
    return e.message
  end
end

def write_to_a_table(time_stamp)
  ActiveRecord::Base.transaction do
    ActiveRecord::Base.connection.execute("INSERT INTO health_check (date,status) VALUES ('#{time_stamp}', 'fine');")
  end
end
于 2020-09-10T08:54:27.130 回答