datasnap连接池使用

xiaoxiao2021-02-28  78

   当开发人员开始创建Delphi的DataSnap应用时很常见的数据库连接定义方式是每个数据模块建立一个连接。这样做将产生大量的数据库连接,并产生很多问题。从Delphi XE开始,EMB提供了Session管理,更容易实现控制客户端连到服务器的数据库连接。客户端应用程序不会知道这些,服务器将完成所有的事情。 当我们创建一个DataSnap服务器时,最好的做法就是定义一个服务器容器(或数据模块)如ServerContainer模块,其中包含DataSnap服务器组件和注册所有的服务器应用程序所需的类。在这个容器中,我们将定义一个负责处理服务器的数据库连接的方法。 作为一个例子,我已经实现了服务器容器上的一个的getConnection方法。这个方法负责为连接池分配连接,这将有每一个客户端连接列表寻找,连接池里包含有每个客户端的连接,当然更简化一点我们可以直接在其上放置一个Connection控件,而不是放置在ServerMethods单元中,从而达到共享数据库连接池的目的。 [delphi]  view plain  copy  print ? private    { Private declarations }    ListofConnection : TDictionary;   ublic    function GetConnection : TSQLConnection;       当服务器收到来自新的客户端的连接到数据库的请求时,getConnection将创建一个新的连接并添加到连接池清单。如果客户已经有了一个连接相关联,getConnection则只返回的一个SqlConnection实例。连接池使用线程ID来控制每个客户端的唯一连接。如果您使用的DataSnap 2010版本,你必须用GetThreadSession方法来实现这个功能。 [delphi]  view plain  copy  print ? function TServerContainer1.GetConnection: TSQLConnection;   var     dbconn : TSQLConnection;   begin     if ListofConnection.ContainsKey(TDSSessionManager.GetThreadSession.Id) then        Result := ListofConnection[TDSSessionManager.GetThreadSession.Id]     else     begin       dbconn := TSQLConnection.Create(nil);       dbconn.Params.Clear;       dbconn.LoadParamsOnConnect := true;       dbconn.ConnectionName := 'DS Employee';       ListofConnection.Add(TDSSessionManager.GetThreadSession.Id, dbconn);       Result := dbconn;     end;   end;       连接定义后,我们需要更新所有数据集使用此连接,这样服务器的所有方法包括create 和运行时的SQL查询都将要调用getConnection方法。 If you are using the VCL Data components (TSQLQuery, TSQLStoredProc, etc…) on your Server DataModules, the onCreate event is a good place to associate the DataSets with the connection, using the following code.     如果您在服务器上DataModules使用VCL的数据组件(TSQLQuery,TSQLStoredProc等...), 在OnCreate事件是一个设置关联数据集的连接的好地方,可以使用下面的代码来设置。 [delphi]  view plain  copy  print ? procedure TServerContainer1.SetConnection(Conn: TSqlConnection);   var     i: integer;   begin     if Conn = nil then        Conn := GetConnection;     else       Conn := Sender;     for i := 0 to ComponentCount - 1 do       if Components is TSQLQuery then          TSQLQuery(Components).SQLConnection := Conn;   end;       为了避免数据库连接泄漏,我们实现了DSServer的OnDisconnect事件。当客户端断开连接时这段持续将运行。 [delphi]  view plain  copy  print ? if GetConnection <> nil then      GetConnection.Close;  

    当然我们也可以用此方法实现数据集和TDataSetProvider的池化处理。

转载请注明原文地址: https://www.6miu.com/read-67440.html

最新回复(0)