应用程序配置
Overview
在本指南中,您可以学习;了解如何配置应用程序连接到MongoDB 的方式以及 MongoDB 如何处理数据。 设立应用应用程序时,需要提供连接字符串或连接 URI,其中包含 Mongoid 用于连接到MongoDB的一设立指令。要学习;了解有关连接字符串的更多信息,请参阅服务器手册中的 连接字符串。
您主要使用指定连接选项和客户端的 mongoid.yml
文件来配置 Mongoid。 要学习;了解有关在设置应用程序时创建 mongoid.yml
文件的更多信息,请参阅以下指南之一:
mongoid.yml 的结构
应用程序的最简单配置是将 Mongoid 配置为连接到位于 localhost:27017
的MongoDB服务器并访问权限名为 myDB
的数据库。 此配置的 mongoid.yml
文件类似于以下文件:
development: clients: default: database: myDB hosts: - localhost:27017
上述文件中的顶级键 development
是指应用程序运行的环境名称。 可能的值包括 development
、test
或 production
。 第三级密钥 default
是指MongoDB客户端名称。 大多数应用程序使用名为 default
的单个客户端。
生成默认配置
如果使用Ruby on Rails 作为应用程序框架,则可以通过运行以下Shell命令在应用程序中生成默认配置文件:
rails g mongoid:config
此命令会在 config/mongoid.yml
创建配置文件。 还会在 config/initializers/mongoid.rb
创建一个初始化程序。 我们建议您在 mongoid.yml
中指定所有设置,但您也可以使用 mongoid.rb
初始化程序来设立配置选项。 mongoid.yml
中的设置始终会覆盖初始化程序中的设置。
如果您使用的不是Ruby on Rails,可以创建 config/mongoid.yml
文件,然后复制并粘贴上一节所示的配置文件。
加载 Mongoid 配置
重要
在使用任何 Mongoid 组件之前,必须配置 Mongoid。 使用或引用组件后,更改配置可能不会应用更改应用于已实例化的组件。
如果您使用的是Ruby on Rails,则 Rails 会自动加载存储在 Rails.env
中的当前环境的 Mongoid 配置。
您还可以通过将以下行添加到 application.rb
文件,将 Mongoid 指定为应用程序的 ORM:
config.generators do |g| g.orm :mongoid end
如果您使用的不是Ruby on Rails,则必须手动加载 Mongoid 配置。 调用 Mongoid.load!
方法,该方法将配置文件路径作为参数:
# Uses automatically detected environment name Mongoid.load!("config/mongoid.yml") # Specifies environment name manually Mongoid.load!("config/mongoid.yml", :development)
Mongoid 通过按顺序检查以下来源来检测环境名称:
如果定义了
Rails
顶级常量:Rails.env
如果定义了
Sinatra
顶级常量:Sinatra::Base.environment
RACK_ENV
环境变量MONGOID_ENV
环境变量。
注意
您还可以直接在Ruby中配置 Mongoid,而无需使用配置文件。 此配置方式不支持环境的概念。 您提供的任何配置都会应用于当前环境。
配置选项
以下带注释的示例mongoid.yml
文件描述了设立每种类型的配置选项的位置,并提供了有关每个选项及其参数的信息。
development: # Configures available database clients. (required) clients: # Defines the default client. (required) default: # Supplies your connection URI, including the database name. uri: mongodb+srv://user:pass@mongo0.example.com/myDB # OR, you can define the parameters separately. # Defines the name of the default database. (required) database: my_db_development # Provides the hosts the client can connect to. # Must be an array of host:port pairs. (required) hosts: - localhost:27017 options: # All options in this section are Ruby driver client options. # To learn more, visit # https://www.mongodb.com/zh-cn/docs/ruby-driver/current/reference/create-client/ # Sets the write concern. (default = { w: 1 }) write: w: 1 # Sets the read preference. Valid options for mode are: :secondary, # :secondary_preferred, :primary, :primary_preferred, :nearest # (default: primary) read: mode: :secondary_preferred tag_sets: # If using tag sets - use: web # Sets name of the user for authentication. user: "user" # Sets password of the user for authentication. password: "password" # Sets user's database roles. roles: - "dbOwner" # Sets the authentication mechanism. Valid options include: # :scram, :scram256, :mongodb_cr, :mongodb_x509, :gssapi, :aws, :plain # MongoDB Server defaults to :scram auth_mech: :scram # Sets the database or source to authenticate the user against. # (default: the database specified above or admin) auth_source: admin # Specifies type of connection. Can be one of: :direct, # :replica_set, :sharded # Set to :direct when connecting to hidden members of a replica set. connect: :direct # Changes the time taken for the server monitors to refresh # their status via hello commands. (default: 10) heartbeat_frequency: 10 # Sets time in seconds for selecting servers for a :nearest read # preference. (default: 0.015) local_threshold: 0.015 # Sets timeout in seconds for selecting a server for an # operation. (default: 30) server_selection_timeout: 30 # Sets maximum number of connections in the connection pool. # (default: 5) max_pool_size: 5 # Sets minimum number of connections in the connection pool. # (default: 1) min_pool_size: 1 # Sets time to wait, in seconds, in the connection pool for a # connection to be checked in before timing out. (default: 5) wait_queue_timeout: 5 # Sets time to wait to establish a connection before timing out, # in seconds. (default: 10) connect_timeout: 10 # Sets name of the replica set to connect to. Servers provided as # seeds that do not belong to this replica set are ignored. replica_set: myRS # Sets compressors to use for wire protocol compression. # (default is to not use compression) compressors: ["zstd", "snappy", "zlib"] # Specified whether to connect to the servers by using ssl. # (default: false) ssl: true # Sets certificate file used to identify the connection for SSL. ssl_cert: /path/to/my.cert # Sets private keyfile used to identify the connection against MongoDB. # 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 # Sets passphrase for the private key. ssl_key_pass_phrase: password123 # Specifies whether to do peer certification validation. # (default: true) ssl_verify: true # Sets file containing concatenated certificate authority # certificates used to validate certs passed from the other end # of the connection. ssl_ca_cert: /path/to/ca.cert # Specifies whether to truncate long log lines. (default: true) truncate_logs: true # Optional Mongoid-specific configuration. options: # Allows BSON::Decimal128 to be parsed and returned directly in # field values. Only has effect when BSON 5+ is present. allow_bson5_decimal128: false # Sets app name that is printed to the MongoDB logs upon establishing # a connection. Value is used as the database name if the database # name is not provided. (default: nil) app_name: nil # When false, callbacks for embedded documents will not be # called. This is the default in 9.0. # Setting this flag to true restores the pre-9.0 behavior, where callbacks # for embedded documents are called, which might lead to stack overflow errors. around_callbacks_for_embeds: false # Sets the async_query_executor for the application. By default the # thread pool executor is set to :immediate. Options are: # - :immediate - Initializes a single +Concurrent::ImmediateExecutor+ # - :global_thread_pool - Initializes a single +Concurrent::ThreadPoolExecutor+ # that uses the +async_query_concurrency+ for the +max_threads+ value. async_query_executor: :immediate # Marks belongs_to associations as required by default, so saving a # model with a missing association triggers a validation error. belongs_to_required_by_default: true # Sets the global discriminator key. discriminator_key: "_type" # Raises an exception when a field is redefined. duplicate_fields_exception: false # Defines how many asynchronous queries can be executed concurrently. # This option should be set only if `async_query_executor` is set # to `:global_thread_pool`. global_executor_concurrency: nil # When this flag is true, any attempt to change the _id of a persisted # document will raise an exception (Errors::ImmutableAttribute). # This is the default in 9.0. Setting this flag to false restores the # pre-9.0 behavior, where changing the _id of a persisted # document might be ignored. immutable_ids: true # Includes the root model name in json serialization. include_root_in_json: false # # Include the _type field in serialization. include_type_for_serialization: false # Specifies whether to join nested persistence contexts for atomic # operations to parent contexts. join_contexts: false # When this flag is false (the default for 9.0), a document that # is created or loaded remembers the storage options that were active # when it was loaded, and will use those same options by default when # saving or reloading itself. # # When this flag is true, a document does not remember the storage # options from when it was loaded/created, and # subsequent updates will need to explicitly set up those options # each time. legacy_persistence_context_behavior: false # Specifies whether to use legacy read-only behavior. To learn more, # visit https://www.mongodb.com/zh-cn/docs/mongoid/current/interact-data/crud legacy_readonly: false # Sets the log level. This must be set before referencing clients # or Mongo.logger, because changes to this option are not be # propagated to any clients and loggers that already exist. log_level: :info # Stores BigDecimals as Decimal128s instead of strings in the db. map_big_decimal_to_decimal128: true # Preloads all models in development, needed when models use # inheritance. preload_models: false # When this flag is true, callbacks for every embedded document will be # called only once, even if the embedded document is embedded in multiple # documents in the root document's dependencies graph. # This is the default in 9.0. Setting this flag to false restores the # pre-9.0 behavior, where callbacks are called for every occurrence of an # embedded document. prevent_multiple_calls_of_embedded_callbacks: true # Raises an error when performing a find operation and no document # matches. raise_not_found_error: true # Raises an error when defining a scope with the same name as an # existing method. scope_overwrite_exception: false # Returns stored times as UTC. use_utc: false # Optional driver-specific configuration. driver_options: # When this flag is off, an aggregation done on a view is performed on # the documents included in that view, instead of all documents in the # collection. When this flag is on, the view filter is ignored. broken_view_aggregate: true # When this flag is set to false, the view options is correctly # propagated to readable methods. broken_view_options: true # When this flag is set to true, the update and replace methods # validate the parameters and raise an error if they are invalid. validate_update_replace: false
基于版本的默认值
Mongoid 支持将特定版本的配置选项设置为其默认值。 当您更新到新的 Mongoid 版本时,这可能很有用。 升级 Mongoid 版本时,请在 Mongoid::Config
上设立以下选项:
Mongoid.configure do |config| config.load_defaults <older version> end
这允许您升级到新版本的 Mongoid,同时使用以前安装的版本中的配置选项。 此功能使您有更多时间对每个更改的行为实现测试,以确保您的代码不会中断或以意外方式运行。 验证应用应用程序按预期运行后,可以删除此代码以使用当前版本的默认配置。
ERb 预处理
加载配置文件时,Mongoid 会使用 ERb 对其进行处理,然后将其解析为 YAML。这允许 Mongoid 在运行时根据环境变量构造配置文件的内容。
由于 Mongoid 在 YAML 解析之前执行 ERb 渲染,因此会评估配置文件中的所有 ERb 指令,包括 YAML 注释中出现的指令。
以下示例mongoid.yml
文件演示了如何引用存储连接字符串的环境变量:
development: clients: default: uri: "<%= ENV['MONGODB_URI'] %>"
提示
从 ERb 输出值时,请确保这些值是有效的 YAML 并根据需要对其进行转义。
时区配置
Mongoid 使用 Active Support 的时区域功能,该功能提供了比 Ruby 标准库更多的功能。 Active Support 允许配置 Time.zone
变量,这是一个线程全局变量,为处理日期和时间值提供上下文。
您可以通过执行以下步骤在应用程序中实现正确的时区域处理:
将操作系统的时区设置为 UTC。
将应用程序默认时区域设置为 UTC,如以下代码所示:
# If using Rails, in `application.rb`: class Application < Rails::Application config.time_zone = 'UTC' end # If not using Rails: Time.zone = 'UTC' 在每个控制器和作业类中,在
before_filter
回调中设立适当的时区域:class ApplicationController < ActionController::Base before_filter :fetch_user, :set_time_zone def set_time_zone Time.zone = @user.time_zone end end 然后,您就可以使用本地时区域的时间。
使用 Active Support 方法而不是Ruby标准库。
使用
Time.zone.now
或Time.current
方法而不是Time.now
使用
Date.current
方法而不是Date.today
Ruby标准库方法(例如
Time.now
和Date.today
)引用系统时区域,而不是Time.zone
变量的值。您可能会误认为这些名称相似的方法,因此我们建议在测试中使用 RuboCop 的 Rails/TimeZone功能。
对MongoDB数据设置时区
MongoDB以 UTC 格式存储所有时间,不包含时区域信息。 Mongoid 模型会加载并返回时间值作为 ActiveSupport::TimeWithZone
的实例。 您可以设立use_utc
选项来控制 Mongoid 在从数据库加载值时如何设置时区域:
false
(默认):Mongoid 使用Time.zone
的值来设立数据库中值的时区域。true
:Mongoid 始终将加载的时间值的时区域设置为 UTC。
use_utc
选项仅影响数据加载方式,不影响数据持久化方式。 示例,如果将 Time
或 ActiveSupport::TimeWithZone
实例分配给时间字段,则无论 use_utc
值如何,都会使用所分配实例的时区域信息。
或者,如果将字符串值分配给时间字段,则会解析字符串中的任何时区域信息。 如果字符串不包含时区域信息,则会根据 Time.zone
值进行解析。
以下代码设置一个 Time.zone
值并演示 Mongoid 如何处理不同的时间字符串:
Time.use_zone("Asia/Kolkata") do # String does not include time zone, so "Asia/Kolkata" is used ghandi.born_at = "1869-10-02 7:10 PM" # Time zone in string (-0600) is used amelia.born_at = "1897-07-24 11:30 -0600" end
SSL/TLS 配置
您可以在应用程序中配置高级 TLS 选项,例如启用或禁用某些密码。 要学习;了解主要的 SSL/TLS 选项,请参阅本指南的“配置选项”部分。
您可以在Ruby驾驶员上设立TLS 上下文钩子。 TLS 上下文钩子是用户提供的 Proc
对象,在驾驶员中创建任何 TLS 套接字连接之前调用。 这些钩子可用于修改套接字使用的根本的OpenSSL::SSL::SSLContext
对象。
要设立TLS 上下文钩子,请将 Proc
添加到 Mongo.tls_context_hooks
大量。 此任务可以在初始化程序中完成。 以下示例添加了一个仅启用 "AES256-SHA"
密码的钩子:
Mongo.tls_context_hooks.push( Proc.new { |context| context.ciphers = ["AES256-SHA"] } )
Mongo.tls_context_hooks
中的每个 Proc
都会传递一个 OpenSSL::SSL::SSLContext
对象作为其唯一参数。 这些 Proc
对象在套接字创建期间按顺序运行。
警告
TLS 上下文钩子是全局性的,会影响应用程序中的所有 Mongo::Client
实例。
要学习;了解有关 TLS 上下文钩子的更多信息,请参阅Ruby驾驶员文档中的修改 SSLContext。
网络压缩
Mongoid 支持压缩传入和传出MongoDB的消息。 此功能由Ruby驾驶员提供,该驱动程序实现了以下支持的算法:
Zstandard(推荐):要使用
zstandard
压缩,必须安装 zstd-Ruby 库。与其他压缩器相比,该压缩器可在相同的 CPU 消耗下产生最高的压缩率。Snappy :要使用
snappy
压缩,您必须安装snappy库。zlib :要使用
zlib
压缩,必须安装zlib库。
要使用传输协议压缩,请在 mongoid.yml
文件中配置驾驶员选项:
development: clients: default: ... options: # Specify compresses to use. (default is no compression) # Accepted values are zstd, zlib, snappy, or a combination compressors: ["zstd", "snappy"]
如果您没有明确请求任何压缩程序,则即使安装了一个或多个压缩程序所需的依赖项,驾驶员也不会使用压缩。
如果指定了多个压缩器,驾驶员会选择MongoDB 部署支持的第一个压缩器。