2016-10-30 11 views
0

타사 서비스를 사용하는 응용 프로그램이 있습니다. 내 응용 프로그램은 DB에 저장하는 해당 서비스에 대한 인증을 만들 수 있습니다. 이 인증은 DB에 있어야 사용할 수 있기 때문에 동일한 트랜잭션에서 커밋 할 수 없습니다. 이 작업을 위해 새 DB 연결을 만들고 즉시 인증 레코드를 커밋 할 스레드를 엽니 다.스레드에서 백그라운드 작업 만들기

이 스레드를 사용하여 문제가있는 것 같습니다. 스레드가 없으면 모든 코드가 원활하게 실행되고, 인증을 사용해야 할 때까지 모든 것이 작동하고 DB에 아직 없으므로 401이 표시됩니다.

아래 상황을 수행 할 수 있습니다. 사용자를 만들면 run_backround_job에 도달 할 때까지 다른 콜백을 트리거합니다. perform_later에 매달려있는 것 같습니다. 스레드 코드를 제거하고 즉시 실행하면 모든 것이 작동합니다. 그러나 어떤 이유로 그것은 그것이 별도의 스레드에있는 경우 작업 대기열에 붙어 있습니다.

class User < ApplicationRecord 
    belongs_to :organization 

    after_create :use_auth 

    def use_auth 
    organization.find_or_create_auth 
    end 
end 

class Organization < ApplicationRecord 
    has_many :authentications 
    has_many :users 

    def find_or_create_auth 
    Thread.new do 
     ApplicationRecord.connection_pool.with_connection do 
     authentications.find_or_create_by(name: name) 
     end 
    end.join.value 
    end 
end 

class Authentication < ApplicationRecord 
    belongs_to :organization 

    after_create :run_background_job 

    def run_background_job 
    AuthBackgroundJob.perform_later(id) 
    end 
end 

레일 (5.0.0) 퓨마 (3.6.0) sidekiq (4.1.4)

답변

1

사용 after_commit :run_background_job :

여기에 무슨 일이 일어나고 있는지 나타내는 코드입니다.

+0

이것은 작동하는 것 같습니다! 하지만 전에는 조금도 이상하지 않다는 것입니다. –

+0

https://github.com/mperham/sidekiq/wiki/FAQ#why-am-i-seeing-a-lot-of-cant-find-modelname- with-id12345-errors-with-sidekiq –

관련 문제