복붙노트

[REDIS] sidekiq의 작업의 실행 시간을 줄일 수

REDIS

sidekiq의 작업의 실행 시간을 줄일 수

나는 현재 레일 서버에서 연락처의 동기화를 포함 응용 프로그램에서 일하고 있습니다. 나는 백그라운드에서 연락처 동기화를 수행하기위한 레디 스 서버와 sidekiq를 사용하고 있습니다. 내 데이터베이스 MongoDB를 내가 ORM로 mongoid 보석을 사용하고 있습니다. 워크 플로우는 다음과 같습니다

다음과 같이 sidekiq의 한 작업은 다음과 같습니다

이제 문제는 sidekiq이 작업을 완료하는 데 시간 미친 양을 취한다는 것입니다. 평균적으로이 작업을 완료하는 데 50 ~ 70 초 소요됩니다.

다음은 관련 파일은

sidekiq.yml

# Sample configuration file for Sidekiq.
# Options here can still be overridden by cmd line args.
#   sidekiq -C config.yml

:verbose: true
:concurrency:  5
:logfile: ./log/sidekiq.log
:pidfile: ./tmp/pids/sidekiq.pid
:queues:
  - [new_wall, 1]#6
  - [contact_wall, 1]#7
  - [email, 1]#5
  - [gcm_chat, 1]#5
  - [contact_address, 1]#7
  - [backlog_contact_address, 5]
  - [comment, 7]
  - [default, 5]

mongoid.yml

development:
  # Configure available database sessions. (required)
  sessions:
    # Defines the default session. (required)
    default:
          # Defines the name of the default database that Mongoid can connect to.
          # (required).
          database: "<%= ENV['DB_NAME']%>"
          # Provides the hosts the default session can connect to. Must be an array
          # of host:port pairs. (required)
          hosts:
            - "<%=ENV['MONGOD_URL']%>"
          #username: "<%= ENV['DB_USERNAME']%>"
          #password: "<%= ENV['DB_PASSWORD']%>"
          options:

            #pool: 12
        # Change the default write concern. (default = { w: 1 })
        # write:
        # w: 1

        # Change the default consistency model to primary, secondary.
        # 'secondary' will send reads to secondaries, 'primary' sends everything
        # to master. (default: primary)
        # read: secondary_preferred

        # How many times Moped should attempt to retry an operation after
        # failure. (default: The number of nodes in the cluster)
        # max_retries: 20

        # The time in seconds that Moped should wait before retrying an
        # operation on failure. (default: 0.25)
        # retry_interval: 0.25
  # Configure Mongoid specific options. (optional)
  options:
    # Includes the root model name in json serialization. (default: false)
    # include_root_in_json: false

    # Include the _type field in serializaion. (default: false)
    # include_type_for_serialization: false

    # Preload all models in development, needed when models use
    # inheritance. (default: false)
    # preload_models: false

    # Protect id and type from mass assignment. (default: true)
    # protect_sensitive_fields: true

    # 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

    # Use Active Support's time zone in conversions. (default: true)
    # use_activesupport_time_zone: true

    # Ensure all times are UTC in the app side. (default: false)
    # use_utc: false
test:
  sessions:
    default:
      database: db_test
      hosts:
        - localhost:27017
      options:
        read: primary
        # In the test environment we lower the retries and retry interval to
        # low amounts for fast failures.
        max_retries: 1
        retry_interval: 0


production:
  # Configure available database sessions. (required)
  sessions:
    # Defines the default session. (required)
    default:
      # Defines the name of the default database that Mongoid can connect to.
      # (required).
      database: "<%= ENV['DB_NAME']%>"
      # Provides the hosts the default session can connect to. Must be an array
      # of host:port pairs. (required)
      hosts:
        - "<%=ENV['MONGOD_URL']%>"
      username: "<%= ENV['DB_USERNAME']%>"
      password: "<%= ENV['DB_PASSWORD']%>"
      pool: 10
      options:

  # Configure Mongoid specific options. (optional)
  options:

Model.rb

def retry_save_contact_dump(c_dump_id)
      c_dump = ContactDump.where(_id: c_dump_id, status: ContactDump::CONTACT_DUMP_CONS[:ERROR]).first
      return false if c_dump.blank?
      user = User.where(_id: c_dump.user_id).first
      puts "retry_save_contact_dump"
      user.save_contacts_with_name(c_dump.contacts)
      c_dump.status = ContactDump::CONTACT_DUMP_CONS[:PROCESSED]
      c_dump.error_msg = ""
      c_dump.save
    rescue => e
      c_dump.status = ContactDump::CONTACT_DUMP_CONS[:CANTSYNC]
      c_dump.error_msg = e.message
      c_dump.save
   end


def save_contacts_with_name(c_array)
    m_num = Person.get_number_digest(self.mobile_number.to_s)
    c_array.each do |n|
      next if m_num == n["hash_mobile_number"]
      p = Person.where(h_m_num: n["hash_mobile_number"]).first_or_create
      save_friend(p) #if p.persisted?
      p.c_names.create(name: n["name"], user_id: self.id)
    end
  end

ContactDump.rb

class ContactDump
  include Mongoid::Document
  include Mongoid::Timestamps::Created
  include Mongoid::Timestamps::Updated

  field :contacts,   type: Array
  field :status,     type: Integer, default: 0
  field :user_id,    type: BSON::ObjectId
  field :error_msg,  type: String

  CONTACT_DUMP_CONS = {FRESH: 0,  PROCESSED: 1, ERROR: 2, CANTSYNC: 3}
end

어떻게 작업의 처리 속도를 높일 수 있습니다? 나는 sidekiq.yml 및 mongoid.yml의 풀에 sidekiq의 동시성을 증가 순열,하지만 도움을 시도했다.

어떻게 WHATSAPP 및 기타 메시징 애플리케이션은 연락처 동기화를 처리합니까?

다른 정보가 필요한 경우 문의하시기 바랍니다. 감사.

편집 :이 질문에 대답 할 수없는 경우, 캔 사람이 나에게 서버를 레일에 연락처를 동기화 할 수있는 다른 방법을 제안 해주십시오.

해결법

  1. ==============================

    1.구출 인덱스.

    구출 인덱스.

    class ContactDump
      index({status: 1})
    end
    
    class Person
      index({h_m_num: 1})
    end
    

    사람은 Person.get_number_digest이 무엇에 따라 더 많은 인덱스를해야 할 수도 있습니다.

    인덱스 실행을 추가 한 후 레이크 dB : mongoid : create_indexes

    또한, 풋를 제거 할, 당신은 심하게 성능을 타격하여 노동자와 풋에, 심지어 때 출력을 볼 수 없습니다 필요가 없습니다!

  2. from https://stackoverflow.com/questions/36221400/reduce-the-execution-time-of-jobs-of-sidekiq by cc-by-sa and MIT license