2016-03-25 4 views
2

В настоящее время я работаю над приложением, которое включает в себя синхронизацию контактов на сервере rails. Я использую сервер redis и sidekiq для синхронизации контактов в фоновом режиме. Моя база данных - mongodb, и я использую мангоидный жемчуг как ORM. Рабочий процесс следующий:Уменьшить время выполнения заданий sidekiq

  1. Контакты по телефону передаются на сервер рельсов через приложение, а затем на сервер рельсов, он помещается в очередь на сервере redis.
  2. Теперь задание cron запускает sidekiq, который соединяется с redis и завершает работу.

Должностная из sidekiq выглядит следующим образом:

  1. имеет множество контактов (размер Шифрование до 3000).
  2. Он должен обрабатывать каждый из этих контактов. Посредством обработки я имею в виду запрос вставки в БД.

Теперь проблема в том, что 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 в sidekiq.yml и пуле mongoid.yml, но никакой помощи.

Как приложения WhatsApp и другие приложения для обмена сообщениями имеют дело с синхронизацией контактов?

Если требуется какая-либо другая информация, обратитесь к нам. Благодарю.

EDIT: Если вы не можете ответить на этот вопрос, можете ли вы предложить мне другие способы синхронизации контактов на сервере rails.

ответ

1

индексы на помощь.

class ContactDump 
    index({status: 1}) 
end 

class Person 
    index({h_m_num: 1}) 
end 

Person может понадобиться несколько индексов в зависимости от того, что ваш Person.get_number_digest делает.

После добавления индекса запуска rake db:mongoid:create_indexes

Также, удалить puts, вам не нужно, чтобы на вашем работника и ставит бьет производительность плохо, даже если вы не можете увидеть результат!

+0

спасибо, я попробую это и обновит после выполнения. – paramvir

+0

Это сработало. спасибо .... Теперь среднее время работы составляет 5 секунд, что было раньше 80 секунд.Это чертовски много улучшений. Спасибо Томасу ... – paramvir

Смежные вопросы