保持跨请求打开与第三方服务的连接

时间:2019-05-22 01:19:57

标签: ruby-on-rails ruby thread-safety singleton

我有这个模块,可以用作第三方服务的适配器:

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')

我的目标是,因为建立连接需要一些时间,所以我希望能够记住它,以便在请求之间进行回收。

问题在于,在类方法中包含实例变量似乎不是线程安全的。所以我想知道什么是正确的方法。

注意:我知道,到目前为止,我没有考虑连接关闭的情况,稍后我会处理。

1 个答案:

答案 0 :(得分:1)

您想要使用可记忆实例的多种配置模式之一进行重构。但是您可以采取一种快速而又变通的解决方法:

TranslateTransform trans = new TranslateTransform(); FixedCircle.RenderTransform = trans; Point oldPoint = FixedCircle.TransformToAncestor(this).Transform(new Point(centerX,centerY)); Point newPoint = FixedCircle.TransformToAncestor(this).Transform(new Point(0,centerY)); var EndX = FixedCircle.Width / 2 + newPoint.X - oldPoint.X - (FixedCircle.Width); var EndY = FixedCircle.Height / 2 + newPoint.Y - oldPoint.Y - (FixedCircle.Height); var a1X = new DoubleAnimation(0, EndX, TimeSpan.FromSeconds(3)); a1X.Completed += (s, e) => { oldPoint = FixedCircle.TransformToAncestor(this).Transform(new Point(0, centerY)); newPoint = FixedCircle.TransformToAncestor(this).Transform(new Point(centerX, centerY)); EndX = FixedCircle.Width / 2 + newPoint.X - oldPoint.X - (FixedCircle.Width); EndY = FixedCircle.Height / 2 + newPoint.Y - oldPoint.Y - (FixedCircle.Height); var a2X = new DoubleAnimation(0, EndX, TimeSpan.FromSeconds(3)); trans.BeginAnimation(TranslateTransform.XProperty, a2X); }; trans.BeginAnimation(TranslateTransform.XProperty, a1X);

config/application.rb

然后

module DanielApp
  class Application < Rails::Application

    def salesforce_client
      @salesforce_client ||= Restforce.new(host: 'test.salesforce.com')
    end 
  end
end 

或者您可以在初始化程序中定义某种全局变量,然后从那里调用它。