我正在尝试构建一个作为Windows服务运行的DataSnap Rest应用程序,但该向导只有“独立的VCL应用程序”,“独立的控制台应用程序”和“ISAPI动态链接库”(我是使用Delphi XE2企业)。有人可以帮助我。感谢。
答案 0 :(得分:5)
如果DataSnap REST向导可以选择创建Windows服务(如何运行应用程序服务器?)会更方便,但是你可以通过一些小问题解决它。
我第一次遇到这个问题时,我创建了一个常规DataSnap REST服务器作为VCL应用程序和常规Windows服务,并将相关部分从REST服务器复制到服务中。只需确保该服务的输出目录与VCL应用程序的目录相同。
服务的.dpr可能如下所示:
program Service;
uses
Vcl.SvcMgr,
Web.WebReq,
IdHTTPWebBrokerBridge,
WebModuleUnit1 in '..\GUI\WebModuleUnit1.pas' {WebModule1: TWebModule},
ServerMethodsUnit1 in '..\GUI\ServerMethodsUnit1.pas' {ServerMethods1: TDSServerModule},
ServerContainerUnit1 in '..\GUI\ServerContainerUnit1.pas' {ServerContainer1: TDataModule},
Unit1 in 'Unit1.pas' {Service1: TService};
{$R *.RES}
begin
if not Application.DelayInitialize or Application.Installing then
Application.Initialize;
if WebRequestHandler <> nil then
WebRequestHandler.WebModuleClass := WebModuleClass;
Application.CreateForm(TService1, Service1);
Application.Run;
end.
服务的主要部分可能如下所示:
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.SvcMgr, Vcl.Dialogs,
IdHTTPWebBrokerBridge, Web.HTTPApp;
type
TService1 = class(TService)
procedure ServiceCreate(Sender: TObject);
procedure ServiceExecute(Sender: TService);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
private
FServer: TIdHTTPWebBrokerBridge;
procedure TerminateThreads;
public
function GetServiceController: TServiceController; override;
end;
var
Service1: TService1;
implementation
{$R *.DFM}
uses
//Datasnap.DSService; // XE2
Datasnap.DSSession; // XE3
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
Service1.Controller(CtrlCode);
end;
{ TService1}
function TService1.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TService1.ServiceCreate(Sender: TObject);
begin
FServer := TIdHTTPWebBrokerBridge.Create(Self);
end;
procedure TService1.ServiceExecute(Sender: TService);
begin
while not Terminated do
begin
Sleep(1000);
ServiceThread.ProcessRequests(False);
end;
end;
procedure TService1.ServiceStart(Sender: TService; var Started: Boolean);
begin
if not FServer.Active then
begin
FServer.Bindings.Clear;
FServer.DefaultPort := 8080;
FServer.Active := True;
end;
end;
procedure TService1.ServiceStop(Sender: TService; var Stopped: Boolean);
begin
TerminateThreads;
FServer.Active := False;
FServer.Bindings.Clear;
ServiceThread.Terminate;
end;
procedure TService1.TerminateThreads;
begin
if TDSSessionManager.Instance <> nil then
TDSSessionManager.Instance.TerminateAllSessions;
end;
end.