애플리케이션 구성
이 페이지의 내용
개요
이 가이드 에서는 애플리케이션 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를 애플리케이션 프레임워크 로 사용하는 경우 다음 셸 명령을 실행 하여 애플리케이션 에서 기본값 구성 파일 생성할 수 있습니다.
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/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 # Allows duplicate indexes to be declared and sent # to the server. The server then validates the indexes and raises an # exception if duplicate indexes are detected. When false, indexes # are validated on the client, which can lead to some indexes # getting silently ignored even if they are not duplicates. # (default: false) allow_duplicate_index_declarations: 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/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는 YAML로 구문 분석하기 전에 ERb를 사용하여 처리합니다. 이를 통해 Mongoid는 환경 변수를 기반으로 런타임에 구성 파일 의 내용을 구성할 수 있습니다.
Mongoid는 YAML 구문 분석 전에 ERb 렌더링을 수행하기 때문에 YAML 주석에 발생하는 지시문을 포함하여 구성 파일 의 모든 ERb 지시문을 평가합니다.
다음 샘플 mongoid.yml
파일 연결 문자열 저장하는 환경 변수를 참조하는 방법을 보여줍니다.
development: clients: default: uri: "<%= ENV['MONGODB_URI'] %>"
팁
ERb에서 값을 출력할 때는 값이 유효한 YAML인지 확인하고 필요에 따라 이스케이프 처리하세요.
표준 시간대 구성
Mongoid는 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 그런 다음 현지 구역 의 시간으로 작업할 수 있습니다.
Ruby 표준 라이브러리 대신 Active Support 메서드를 사용합니다.
Time.now
대신Time.zone.now
또는Time.current
메서드 사용Date.today
대신Date.current
메서드 사용
Time.now
및Date.today
와 같은 Ruby 표준 라이브러리 메서드는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 컨텍스트 후크는 운전자 에서 TLS 소켓 연결이 생성되기 전에 호출되는 사용자 제공 Proc
객체입니다. 이러한 후크를 사용하여 소켓에서 사용하는 기본 OpenSSL::SSL::SSLContext
객체 수정할 수 있습니다.
TLS 컨텍스트 훅을 설정하다 하려면 Mongo.tls_context_hooks
배열 에 Proc
을 추가합니다. 이 작업 이니셜라이저에서 수행할 수 있습니다. 다음 예시 "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 소비량으로 가장 높은 압축률을 생성합니다.
유선 프로토콜 압축을 사용하려면 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 deployment 에서 지원하는 첫 번째 압축기를 선택합니다.