配置
在此页面上
Mongoid 通常通过指定选项和客户端的 mongoid.yml
文件进行配置。最简单的配置如下:将 Mongoid 配置为与位于“localhost:27017”的 MongoDB Server 通信并使用名为“mongoid”的数据库。
development: clients: default: database: mongoid hosts: - localhost:27017
配置文件中的顶级密钥(上例中的 development
)指的是应用程序的执行环境名称,即 development
、test
或 production
。以上示例的第三级密钥 default
指的是 Mongo 客户端名称。大多数应用程序将使用名为 default
的单一客户端。
生成默认配置
如果您使用的是 Ruby on Rails,则可以通过运行以下命令让 Mongoid 为您生成默认配置文件:
rails g mongoid:config
配置文件将放在 config/mongoid.yml
中。
如果您使用的不是 Ruby on Rails,则可以复制上面给出的最低配置,并将其另存为 config/mongoid.yml
。
加载 Mongoid 配置
如果正在使用 Ruby on Rails,则在加载应用程序时,系统会自动加载存储在 Rails.env
中的当前环境的 Mongoid 配置。
您可能需要通过将以下内容添加到 application.rb
,来将应用程序的 ORM 配置为 Mongoid:
config.generators do |g| g.orm :mongoid end
如果您使用的不是 Ruby on Rails,则必须手动加载 Mongoid 配置。此操作可通过 Mongoid.load!
方法来完成,该方法会将配置文件路径作为参数,如下所示:
# Use automatically detected environment name Mongoid.load!("path/to/your/mongoid.yml") # Specify environment name manually Mongoid.load!("path/to/your/mongoid.yml", :production)
如果要求 Mongoid 自动检测环境名称,它会为此按顺序检查以下来源:
如果定义了
Rails
顶级常量,则检查Rails.env
。如果定义了
Sinatra
顶级常量,则检查Sinatra::Base.environment
。RACK_ENV
环境变量。MONGOID_ENV
环境变量。
还可以直接在 Ruby 中配置 Mongoid,而无需使用配置文件。这种配置方式不支持环境的概念(无论提供什么配置,它都会应用于当前环境)但它确实支持定义多个客户端。
Mongoid.configure do |config| config.clients.default = { hosts: ['localhost:27017'], database: 'my_db', } config.log_level = :warn end
注意
在使用或引用 Mongoid 的任何组件之前,必须先对 Mongoid 进行配置。如果在使用或引用组件后更改配置,则更改可能不会应用于已实例化的组件。
Mongoid 配置选项
以下带注释的示例 mongoid.yml
演示了如何配置 Mongoid。
Mongoid 委托给 Ruby 驱动程序进行客户端配置。有关驱动程序选项的详细信息,请查阅驱动程序文档。
development: # Configure available database clients. (required) clients: # Define the default client. (required) default: # A uri may be defined for a client: # uri: 'mongodb://user:password@myhost1.mydomain.com:27017/my_db' # Please see driver documentation for details. Alternatively, you can # define the following: # # Define the name of the default database that Mongoid can connect to. # (required). database: my_db # Provide the hosts the default client can connect to. Must be an array # of host:port pairs. (required) hosts: - myhost1.mydomain.com:27017 - myhost2.mydomain.com:27017 - myhost3.mydomain.com:27017 options: # These options are Ruby driver options, documented in # https://mongodb.com/zh-cn/docs/ruby-driver/current/reference/create-client/ # Change the default write concern. (default = { w: 1 }) write: w: 1 # Change the default read preference. Valid options for mode are: :secondary, # :secondary_preferred, :primary, :primary_preferred, :nearest # (default: primary) read: mode: :secondary_preferred tag_sets: - use: web # The name of the user for authentication. user: 'user' # The password of the user for authentication. password: 'password' # The user's database roles. roles: - 'dbOwner' # Change the default authentication mechanism. Please see the # driver documentation linked above for details on how to configure # authentication. Valid options are :aws, :gssapi, :mongodb_cr, # :mongodb_x509, :plain, :scram and :scram256 (default on 3.0 # and higher servers is :scram, default on 2.6 servers is :plain) auth_mech: :scram # Specify the auth source, i.e. the database or other source which # contains the user's login credentials. Allowed values for auth source # depend on the authentication mechanism, as explained in the server documentation: # https://mongodb.com/zh-cn/docs/manual/reference/connection-string/#mongodb-urioption-urioption.authSource # If no auth source is specified, the default auth source as # determined by the driver will be used. Please refer to: # https://mongodb.com/zh-cn/docs/ruby-driver/current/reference/authentication/#auth-source auth_source: admin # Connect directly to and perform all operations on the specified # server, bypassing replica set node discovery and monitoring. # Exactly one host address must be specified. (default: false) #direct_connection: true # Deprecated. Force the driver to connect in a specific way instead # of automatically discovering the deployment type and connecting # accordingly. To connect directly to a replica set node bypassing # node discovery and monitoring, use direct_connection: true instead # of this option. Possible values: :direct, :replica_set, :sharded. # (default: none) #connect: :direct # Change the default time in seconds the server monitors refresh their status # via hello commands. (default: 10) heartbeat_frequency: 10 # The time in seconds for selecting servers for a near read preference. (default: 0.015) local_threshold: 0.015 # The timeout in seconds for selecting a server for an operation. (default: 30) server_selection_timeout: 30 # The maximum number of connections in the connection pool. (default: 5) max_pool_size: 5 # The minimum number of connections in the connection pool. (default: 1) min_pool_size: 1 # The time to wait, in seconds, in the connection pool for a connection # to be checked in before timing out. (default: 1) wait_queue_timeout: 1 # The time to wait to establish a connection before timing out, in seconds. # (default: 10) connect_timeout: 10 # How long to wait for a response for each operation sent to the # server. This timeout should be set to a value larger than the # processing time for the longest operation that will be executed # by the application. Note that this is a client-side timeout; # the server may continue executing an operation after the client # aborts it with the SocketTimeout exception. # (default: nil, meaning no timeout) socket_timeout: 5 # The name of the replica set to connect to. Servers provided as seeds that do # not belong to this replica set will be ignored. replica_set: my_replica_set # Whether to connect to the servers via ssl. (default: false) ssl: true # The certificate file used to identify the connection against MongoDB. ssl_cert: /path/to/my.cert # The private keyfile used to identify the connection against MongoDB. # Note that even if the key is stored in the same file as the certificate, # both need to be explicitly specified. ssl_key: /path/to/my.key # A passphrase for the private key. ssl_key_pass_phrase: password # Whether or not to do peer certification validation. (default: true) ssl_verify: true # The file containing a set of concatenated certification authority certifications # used to validate certs passed from the other end of the connection. ssl_ca_cert: /path/to/ca.cert # Compressors to use. (default is to not use compression) compressors: [zlib] # Configure Mongoid-specific options. (optional) options: # Application name that is printed to the MongoDB logs upon establishing # a connection in server versions 3.4 or greater. Note that the name # cannot exceed 128 bytes in length. It is also used as the database name # if the database name is not explicitly defined. (default: nil) app_name: MyApplicationName # Type of executor for queries scheduled using ``load_async`` method. # # There are two possible values for this option: # # - :immediate - Queries will be immediately executed on a current thread. # This is the default option. # - :global_thread_pool - Queries will be executed asynchronously in # background using a thread pool. #async_query_executor: :immediate # Mark belongs_to associations as required by default, so that saving a # model with a missing belongs_to association will trigger a validation # error. (default: true) belongs_to_required_by_default: true # (Deprecated) Maintain broken behavior of sum over empty result sets for backwards # compatibility. When calculating a sum on a field with a null context, # for example: # # Product.none.sum(:price) # # ... return field name (`:price') instead of 0. # # When calculating a sum via a database query with an empty result set, # for example: # # Product.where(impossible_condition: true).sum(:price) # # ... return nil instead of 0. # (default: false) #broken_aggregables: true # (Deprecated) Ignore aliased fields in embedded documents when performing pluck and # distinct operations, for backwards compatibility. # (default: false) #broken_alias_handling: true # (Deprecated) Maintain broken `and' method behavior that existed in Mongoid 7.3 # and earlier for backwards compatibility: in some situations, conditions # already present in a Criteria object would be replaced by newer # conditions when `and' method is used instead of the new conditions # being added to the existing conditions. This would happen when using # the same operator on the same field multiple times. For example: # # Band.where(id: 1).and({year: {'$in' => [2020]}}, {year: {'$in' => [2021]}}).where(id: 2) # # yields the following criteria: # # <Mongoid::Criteria # selector: {"_id"=>1, "year"=>{"$in"=>[2020]}, "$and"=>[{"_id"=>2}]} # options: {} # class: Band # embedded: false> # # This is obviously incorrect as the {"$in"=>[2021]} clause is lost. # Notice that the clause is only lost when both clauses are added using # the #and method. # (default: false) #broken_and: true # (Deprecated) When exiting a nested `with_scope' block, set the current scope to # nil instead of the parent scope for backwards compatibility. # (default: false) #broken_scoping: true # (Deprecated) Maintain broken update behavior in some cases for backwards # compatibility. # # In Mongoid 7.3 and earlier, when assigning a value to an embedded # document, then setting it to nil, then assigning the original value # to it again, the second update would not work and the value for the # embedded document would remain nil. Take this case: # # canvas.palette = palette # canvas.palette = nil # canvas.palette = palette # # ... where canvas embeds_one palette. # # In Mongoid 7.3 and earlier, canvas.palette would be nil when we would # expect it to be palette. Set this option to true to keep this behavior, # set the option to false to perform the second update correctly. # (default: false) #broken_updates: true # (Deprecated) Time objects in Ruby have nanosecond precision, whereas MongoDB server # can only store times with millisecond precision. Set this option to # true to truncate times to millisecond precision when performing # queries on already loaded embedded associations (this is also called # "embedded matching" and is done completely in Ruby), to obtain the # same query results when performing time comparisons regardless of # which documents are being queried. Setting this option to false will # produce different results for queries on embedded associations that # are already loaded into memory vs queries on unloaded associations and # top-level models. (default: true) #compare_time_by_ms: false # Set the global discriminator key. (default: "_type") discriminator_key: "_type" # Raise an exception when a field is redefined. (default: false) duplicate_fields_exception: false # Defines how many asynchronous queries can be executed concurrently. # This option should be set only if `async_query_executor` option is set # to `:global_thread_pool`. #global_executor_concurrency: nil # Include the root model name in json serialization. (default: false) include_root_in_json: false # Include the _type field in serialization. (default: false) include_type_for_serialization: false # Whether to join nested persistence contexts for atomic operations # to parent contexts by default. (default: false) join_contexts: false # (Deprecated) When this flag is true, the attributes method on a document will return # a BSON::Document when that document is retrieved from the database, and # a Hash otherwise. When this flag is false, the attributes method will # always return a Hash. (default: false) #legacy_attributes: true # (Deprecated) Maintain legacy behavior of pluck and distinct, which does not demongoize # values on returning them. Setting this option to false will cause # pluck and distinct to return demongoized values. Setting this option to # false will also allow retrieving *_translations fields from pluck and # distinct and will return embedded values themselves (i.e. without # putting them in a hash). # (default: false) #legacy_pluck_distinct: true # When this flag is false, a document will become read-only only once the # #readonly! method is called, and an error will be raised on attempting # to save or update such documents, instead of just on delete. When this # flag is true, a document is only read-only if it has been projected # using #only or #without, and read-only documents will not be # deletable/destroyable, but will be savable/updatable. # When this feature flag is turned on, the read-only state will be reset on # reload, but when it is turned off, it won't be. # (default: false) #legacy_readonly: true # (Deprecated) Maintain legacy behavior of === on Mongoid document classes, which # returns true in a number of cases where Ruby's === implementation would # return false. Note that the behavior of === on Mongoid document # instances differs from both the behavior of === on document classes # and from Ruby's behavior of === on simple object instances regardless # of the value of this option. # (default: false) #legacy_triple_equals: true # Set the Mongoid and Ruby driver log levels when Mongoid is not using # Ruby on Rails logger instance. (default: :info) log_level: :info # When using the BigDecimal field type, store the value in the database # as a BSON::Decimal128 instead of a string. (default: true) #map_big_decimal_to_decimal128: true # (Deprecated) Force ``BSON::ObjectId#as_json`` method to return the hash # { "$oid" => id.to_s }. When this option is false, and bson-ruby 5 # is used, the return value will be the hexadecimal ObjectId string only. # (default: false) #object_id_as_json_oid: true # (Deprecated) When chaining the same operators that use the same field, setting this # feature flag to false will cause those operators to be combined using an # and. Setting this feature flag to true will cause the later chained # operators to overwrite the earlier ones. (default: false) #overwrite_chained_operators: false # Preload all models in development, needed when models use # inheritance. (default: false) preload_models: false # Raise an error when performing a #find and the document is not found. # (default: true) raise_not_found_error: true # Raise an error when defining a scope with the same name as an # existing method. (default: false) scope_overwrite_exception: false # (Deprecated) Use ActiveSupport's time zone in time operations instead of # the Ruby default time zone. See the time zone section below for # further information. (default: true) use_activesupport_time_zone: true # Return stored times as UTC. See the time zone section below for # further information. Most applications should not use this option. # (default: false) use_utc: false # (Deprecated) In MongoDB 4.0 and earlier, set whether to create # indexes in the background by default. (default: false) background_indexing: false # Configure driver-specific options. (optional) driver_options: # When this flag is turned off, inline options will be correctly # propagated to Mongoid and Driver finder methods. When this flag is turned # on those options will be ignored. For example, with this flag turned # off, Band.all.limit(1).count will take the limit into account, while # when this flag is turned on, that limit is ignored. The affected driver # methods are: aggregate, count, count_documents, distinct, and # estimated_document_count. The corresponding Mongoid methods are also # affected. (default: false, driver version: 2.18.0+) #broken_view_options: false # Validates that there are no atomic operators (those that start with $) # in the root of a replacement document, and that there are only atomic # operators at the root of an update document. If this feature flag is on, # an error will be raised on an invalid update or replacement document, # if not, a warning will be output to the logs. This flag does not affect # Mongoid as of 8.0, but will affect calls to driver update/replace # methods. (default: false, driver version: 2.18.0+) #validate_update_replace: false
基于版本的默认值
Mongoid 支持将特定版本的配置选项设置为默认值。这对于升级到新的 Mongoid 版本非常有用。升级 Mongoid 版本时,应在 Mongoid::Config
上设置以下内容:
Mongoid.configure do |config| config.load_defaults <OLD VERSION> end
这样,当升级到新版本的 Mongoid 时,您的代码将使用上一个 Mongoid 版本中的配置选项来运行。然后,您可以逐一更改新版本的功能标志,并测试您的代码是否仍按预期运行。一旦所有新功能标志都被考虑在内,就可以更改对 load_defaults
的调用以接受新版本,并可删除所有已更改的功能标志。例如,假设我们要从 7.5 升级到 8.0。在这两个版本之间,仅添加了两个功能标志:legacy_attributes
和 map_big_decimal_to_decimal128
。升级到 Mongoid 8 之前,可以添加以下这一行:
Mongoid.configure do |config| config.load_defaults 7.5 end
现在,升级后,这两个功能标志将默认为其 7.5 功能(legacy_attributes: true, map_big_decimal_to_decimal128: false
)。现在,您可以逐一设置这些功能标志,并将它们转换为 8.0 版本的行为:
Mongoid.configure do |config| config.load_defaults 7.5 config.legacy_attributes = false # config.map_big_decimal_to_decimal128 = true end
建议一次执行一个操作,因此我将第二个标志注释掉。验证代码在关闭 legacy_attributes
标志的情况下按预期工作后,可取消对 map_big_decimal_to_decimal128
设置的注释。一旦该功能也得到验证,就可以删除这两行,并将 load_defaults
替换为:
Mongoid.configure do |config| config.load_defaults 8.0 end
ERb 预处理
加载配置文件时,Mongoid 会先使用 ERb 对其进行处理,然后将其解析为 YAML。由此能够实现的操作包括基于环境变量构建运行时配置文件的内容:
development: clients: default: uri: "<%= ENV['MONGODB_URI'] %>"
注意
从 ERb 输出值时,请确保这些值是有效的 YAML 并根据需要对其进行转义。
注意
由于 ERb 渲染是在 YAML 解析之前执行的,因此会评估配置文件中的所有 ERb 指令,包括 YAML 注释中出现的指令。
日志记录
对日志记录进行配置时,请务必记住:Mongoid 在 MongoDB Ruby 驱动程序之上提供了一个模型层,并且该驱动程序会将 CRUD 操作分派给 MongoDB 部署。因此,使用 Mongoid 的应用程序中有一些日志输出来自 Mongoid 本身,还有一些来自 Ruby 驱动程序。
Mongo 客户端是 Ruby 驱动程序客户端实例,因此 Mongo 客户端的记录器是 Ruby 驱动程序记录器,而不是 Mongoid 记录器。换言之,
# Ruby driver logger, not Mongoid logger Mongoid.client(:default).logger
根据 Ruby on Rails 应用程序中是否使用 Mongoid,以及 Mongoid 和 Ruby 驱动程序的配置方式,它们可能会使用相同的记录器实例或不同的实例(可能具有不同配置)。
在 Ruby on Rails 应用程序中
在 Ruby on Rails 应用程序中使用 Mongoid 时,默认情况下,Mongoid 会从 Rails 继承记录器和日志级别,并将驱动程序的记录器设置为同一记录器实例:
Rails.logger === Mongoid.logger # => true Mongoid.logger === Mongo::Logger.logger # => true
要更改日志级别,请使用 标准 Rails 配置 。将以下内容放入一个环境配置文件中,例如config/environments/production.rb
:
Rails.application.configure do config.log_level = :debug end
注意
当 Mongoid 在 Rails 应用程序中运行时,不使用log_level
Mongoid 配置选项,因为在这种情况下,Mongoid 会继承 Rails 的日志级别。
要以不同于 Rails 记录器的方式配置 Mongoid 或驱动程序记录器,请使用初始化程序,如下所示:
Rails.application.configure do config.after_initialize do # Change Mongoid log destination and/or level Mongoid.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end # Change driver log destination and/or level Mongo::Logger.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end end end
注意
目前,Ruby 标准库 Logger
中没有任何预配可以返回记录器正在使用的日志设备(即 IO
对象)。例如,要将 Mongoid 和/或 Ruby 驱动程序记录到标准 Rails 日志文件(例如 log/development.log
),但采用的日志级别不同于标准 Rails 记录器 (Rails.logger
),则必须单独打开该文件,并将生成的 IO
对象传递给 Logger
构造函数。
注意
由于默认情况下 Mongoid 会将其自己的记录器和驱动程序的记录器设置为与 Rails 记录器相同的实例,因此修改其中任一实例都会影响所有这三个实例。例如,以下代码会更改所有三个记录器的日志级别,除非应用程序如上所述将单独的 Logger
实例分配给 Mongo::Logger.logger
:
Mongoid::Logger.logger.level = Logger::DEBUG
独立运行的实例
当未加载到 Ruby on Rails 应用程序中时,Mongoid 会遵循log_level
顶级配置选项。 它可以在配置文件中给出,如下所示:
development: clients: default: # ... options: log_level: :debug
……或者在配置 Mongoid inline 时:
Mongoid.configure do |config| config.log_level = :debug end
Mongoid 7.1 及更高版本中的默认日志目标是标准错误。Mongoid 7.0 及更低版本中的默认日志目标是标准输出。要更改日志目标,请按以下步骤创建新记录器实例:
Mongoid.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end
要更改 Ruby 驱动程序日志级别或目标:
Mongo::Logger.logger = Logger.new(STDERR).tap do |logger| logger.level = Logger::DEBUG end
要对驱动程序记录器采用与 Mongoid 记录器相同的设置,请执行以下操作:
Mongo::Logger.logger = Mongoid.logger
注意
以独立模式运行时,Mongoid 不会更改驱动程序的记录器。
时区
Ruby 在标准库中对时区的支持有限。ActiveSupport(MongoID 所依赖的对象)提供了更全面的时区支持。重要的是,Ruby 和 ActiveSupport 可配置不同的默认时区。
虽然在 Ruby 中对时区的全面处理超出本教程的范围,但要实现正确的时区处理,最简单可靠的方法如下:
将操作系统的时区设置为 UTC。例如,在 Linux 上:
cp /usr/share/zoneinfo/UTC /etc/localtime
将 ActiveSupport 的时区设置为 UTC:
# If using Rails, in application.rb: class Application < Rails::Application config.time_zone = 'UTC' end # If not using Rails: Time.zone = 'UTC'
以 UTC 格式存储并保留所有时间。按 UTC 时间执行所有计算。
处理采用本地时间的用户输入时,尽快将此类用户输入转换为 UTC 时间,然后处理 UTC 时间。
对时间进行渲染或以其他方式呈现时间时,在实际渲染过程中,先执行所有相关计算,然后将时间转换为本地时间。
日期到时间(例如,某一天开始或结束的时间)的转换是常见的错误来源。在进行此类转换时,一般应明确指定日期所处的时区。
使用 Mongoid 的应用程序通常应如上所述配置 ActiveSupport 的时区,然后使用 Time.zone
而不是 Time
(例如 Time.zone.now
而不是 Time.now
)来调用 ActiveSupport 时区机制。当系统时区并非 UTC 时(此类情况在开发环境中很常见),这也有助于获得正确的结果。
请注意,MongoDB 以 UTC 格式存储所有时间,其中不包含时区信息。
Mongoid 提供以下与时区相关的配置选项:
use_activesupport_time_zone
:此选项已弃用,将在 Mongoid 9.0 中删除,并始终为 true。如果为 true(默认值),则首选使用
ActiveSupport::TimeWithZone
来处理时间。Time
类型字段中的值将作为ActiveSupport::TimeWithZone
的实例返回。当解析不包含时区信息的时间时(例如使用 mongo 将字符串或数组转换为时间),假定时间是在 ActiveSupport 的时区中指定的。这是默认设置。如果为 false,则优先使用 Ruby 标准库
Time
类来处理时间。类型为Time
的字段中的值将作为Time
实例返回。当解析没有时区信息的时间时,假设时间是在 Ruby 时区中指定的。请注意,
use_activesupport_time_zone
设置不会影响类型为Date
或DateTime
的字段,这些字段的值分别使用Date
和DateTime
类。另请注意,Mongoid 仍可根据需要在内部同时使用
Time
和ActiveSupport::TimeWithZone
类,而不考虑use_activesupport_time_zone
设置如何。use_utc
:如果为 true,则存储在 MongoDB 中的时间将以 UTC 时间返回。如果为 false,则按本地时间返回存储在 MongoDB 中的时间(作为Time
或ActiveSupport::TimeWithZone
的实例,分别位于 Ruby 默认时区或 ActiveSupport 时区,具体取决于use_activesupport_time_zone
设置的值)。默认值为 false。use_utc
设置不会影响时间解析方式——当解析的输入不包含时区信息时,始终按当地时间进行解析。要解析 UTC 格式的日期,请将系统/Ruby 或 ActiveSupport 时区设置为 UTC(如上所述,将所有三个时区设置为 UTC 能够最大限度减少麻烦)。建议将
use_activesupport_time_zone
设置为 true,将Time.zone
设置为 UTC(并在所有与时间相关的操作中使用 ActiveSupport 时间机制),而不是将use_utc
设置为 true。
请注意,use_activesupport_time_zone
和 use_utc
选项不会丢弃可用的时区信息。例如,某个时间实例确实具有关联的时区,那么当 use_activesupport_time_zone
为 true 时,即使该时区不同于 ActiveSupport 配置的时区,也会使用该时区。
配置 SSLContext
可能需要在应用程序中进一步配置 TLS 选项,例如启用或禁用某些密码。
这可以通过在 Ruby 驱动程序上设置 TLS 上下文钩子来实现——TLS 上下文钩子由用户提供,是套接字使用的 Proc``s that will be invoked before any TLS socket
connection in the driver and can be used to modify the underlying
``OpenSSL::SSL::SSLContext
对象。
要设置 TLS 上下文钩子,请添加 Proc``s to the ``Mongo.tls_context_hooks
数组。此操作可在初始化程序中完成。下面的示例添加了一个仅启用“AES256-SHA”密码的钩子。
Mongo.tls_context_hooks.push( Proc.new { |context| context.ciphers = ["AES256-SHA"] } ) # Only the AES256-SHA cipher will be enabled from this point forward
Mongo.tls_context_hooks
中的每个 Proc
都会传递一个 OpenSSL::SSL::SSLContext
对象作为其唯一参数。这些过程将在套接字创建期间按顺序执行。
警告
TLS 上下文钩子是全局性的,会影响应用程序中的所有 Mongo::Client
实例。
有关 TLS 上下文钩子的详情,包括分配和删除此类钩子的最佳实践,请参阅 Ruby 驱动程序文档。
客户端加密
加载配置文件时,Mongoid 允许该文件包含 BSON::Binary
实例,这些实例用于在模式映射中指定 keyId
以进行客户端加密,如以下示例所示:
development: clients: default: database: blog_development hosts: [localhost:27017] options: auto_encryption_options: key_vault_namespace: 'keyvault.datakeys' kms_providers: local: key: "z7iYiYKLuYymEWtk4kfny1ESBwwFdA58qMqff96A8ghiOcIK75lJGPUIocku8LOFjQuEgeIP4xlln3s7r93FV9J5sAE7zg8U" schema_map: blog_development.comments: properties: message: encrypt: keyId: - !ruby/object:BSON::Binary data: !binary |- R/AgNcxASFiiJWKXqWGo5w== type: :uuid bsonType: "string" algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" bsonType: "object"
与分叉服务器一起使用
将 Mongoid 与分叉 Web 服务器(例如 Puma、Unicorn 或 Passenger)一起使用时,建议在分叉之前不要对父进程中的 Mongoid 模型执行任何操作。
当进程分叉时,Ruby 线程不会传输到子进程,而且 Ruby 驱动程序客户端对象会失去后台监控。在部署状态发生变化(例如由于网络错误、维护事件)之前,应用程序通常看起来可以正常运行,此时应用程序在执行 MongoDB 操作时可能会开始出现 NoServerAvailable
异常。
如果父进程需要在 MongoDB 数据库上执行操作,请在复制进程后重置 Workers 的所有客户端。如何执行此操作取决于所使用的 Web 服务器。
如果复制子进程后,父进程不需要在 MongoDB 数据库上执行操作,则在复制子进程之前关闭父进程的客户端。如果父进程在 Mongo 客户端上执行操作但不关闭该客户端,则只要父进程保持活动状态,父进程就会继续占用集群的连接槽,并继续监控集群。
注意
此处所述的关闭/重新连接模式应与 Ruby 驱动程序版本 2.6.2 或更高版本一起使用。以前的驱动程序版本在重新连接时不会重新创建监控线程。
Puma
使用 on_worker_boot
钩子重新连接 Workers 中的客户端,使用 before_fork
钩子关闭父进程中的客户端(Puma 文档):
on_worker_boot do if defined?(Mongoid) Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end else raise "Mongoid is not loaded. You may have forgotten to enable app preloading." end end before_fork do if defined?(Mongoid) Mongoid.disconnect_clients end end
Unicorn
使用 after_fork
钩子重新连接工作进程中的客户端,并使用 before_fork
钩子关闭父进程中的客户端(Unicorn 文档):
after_fork do |server, worker| if defined?(Mongoid) Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end else raise "Mongoid is not loaded. You may have forgotten to enable app preloading." end end before_fork do |server, worker| if defined?(Mongoid) Mongoid.disconnect_clients end end
Passenger
使用 starting_worker_process
钩子重新连接工作进程中的客户端(Passenger 文档)。在工作进程分叉之前,Passenger 中似乎不会出现在父进程中调用的钩子。
if defined?(PhusionPassenger) PhusionPassenger.on_event(:starting_worker_process) do |forked| if forked Mongoid::Clients.clients.each do |name, client| client.close client.reconnect end end end end
查询缓存中间件
注意
与 Ruby 驱动程序版本2.15或更高版本一起使用时,Mongoid 的 查询缓存中间件 会委托给驱动程序的 查询缓存中间件。
Mongoid 提供了一个 Rack 中间件,该中间件在每个网络请求期间启用查询缓存。 以下示例了如何在Ruby on Rails应用程序中启用查询缓存中间件:
# config/application.rb # Add Mongoid::QueryCache::Middleware at the bottom of the middleware stack # or before other middleware that queries MongoDB. config.middleware.use Mongoid::QueryCache::Middleware
请参阅 Rails on Rack 指南 有关在 Rails 应用程序中使用 Rack 中间件的更多信息。
开发配置
驱动程序的默认配置适用于生产部署。在开发过程中,可以对某些设置进行调整,以提供更好的开发体验。
:server_selection_timeout
:如果您的 MongoDB Server 在本地运行,并且您会手动启动它,请将此值设置为较低的值(例如1
)。如果没有服务器正在运行,则较低的服务器选择超时会导致驱动程序快速失败。
建议的开发配置示例:
development: clients: default: database: mongoid hosts: - localhost:27017 options: server_selection_timeout: 1