跨请求保持与第三方服务的连接打开
Keep a connection to a third party service open across requests
我有这个模块可以用作第 3 方服务的适配器:
module Salesforce
class ConnectionService
class << self
def client
@client ||= Restforce.new(
# Connection Params
)
end
delegate :query, :create!, :update!, :upsert!, to: :client
end
end
end
想法是将其命名为:
Salesforce::ConnectionService.query('select things from remote service')
我的目标是,因为建立连接需要一些时间,所以我希望能够记住它以便跨请求回收它。
问题是 class 方法中的实例变量似乎不是线程安全的。所以我想知道什么是正确的方法。
注意:我知道暂时不考虑连接关闭的情况,以后再处理。
您想使用记忆实例的众多配置模式之一进行重构。但是你可以采取 quick-and-dirty 解决方法:
config/application.rb
:
module DanielApp
class Application < Rails::Application
def salesforce_client
@salesforce_client ||= Restforce.new(host: 'test.salesforce.com')
end
end
end
那么,
Rails.application.salesforce_client.query("select Id, Something__c from Account where Id = 'someid'")
或者您可以在初始化程序中定义某种全局变量,然后从那里调用它。
我有这个模块可以用作第 3 方服务的适配器:
module Salesforce
class ConnectionService
class << self
def client
@client ||= Restforce.new(
# Connection Params
)
end
delegate :query, :create!, :update!, :upsert!, to: :client
end
end
end
想法是将其命名为:
Salesforce::ConnectionService.query('select things from remote service')
我的目标是,因为建立连接需要一些时间,所以我希望能够记住它以便跨请求回收它。
问题是 class 方法中的实例变量似乎不是线程安全的。所以我想知道什么是正确的方法。
注意:我知道暂时不考虑连接关闭的情况,以后再处理。
您想使用记忆实例的众多配置模式之一进行重构。但是你可以采取 quick-and-dirty 解决方法:
config/application.rb
:
module DanielApp
class Application < Rails::Application
def salesforce_client
@salesforce_client ||= Restforce.new(host: 'test.salesforce.com')
end
end
end
那么,
Rails.application.salesforce_client.query("select Id, Something__c from Account where Id = 'someid'")
或者您可以在初始化程序中定义某种全局变量,然后从那里调用它。