本文作者:icy

mORMot2:现代Pascal的高性能ORM与Web服务框架

icy 昨天 20 抢沙发
mORMot2:现代Pascal的高性能ORM与Web服务框架摘要: mORMot2:现代Pascal的高性能ORM与Web服务框架 项目概述 mORMot2是一个用现代Object Pascal(Delphi/Free Pascal)编写的开源框架...

mORMot2:现代Pascal的高性能ORM与Web服务框架

mORMot2:现代Pascal的高性能ORM与Web服务框架

项目概述

mORMot2是一个用现代Object Pascal(Delphi/Free Pascal)编写的开源框架,专注于提供高性能的ORM(对象关系映射)和Web服务功能。作为mORMot框架的下一代版本,它继承了前代产品的优秀特性,同时在性能、功能和架构上进行了全面升级。

核心特性

1. 高性能ORM

  • 零RTTI(运行时类型信息)设计,编译时生成代码

  • 支持多种数据库后端(SQLite3、PostgreSQL、MySQL、Oracle等)

  • 强大的查询优化和缓存机制

  • 类型安全的数据库操作

2. RESTful Web服务

  • 内置HTTP/HTTPS服务器

  • 自动生成OpenAPI文档

  • 支持JSON、XML等多种数据格式

  • 完整的认证和授权机制

3. 现代架构

  • 基于接口的编程模型

  • 依赖注入容器

  • 事件驱动设计

  • 微服务友好

安装与配置

环境要求

  • Delphi 10.4+ 或 Free Pascal 3.2.0+

  • 支持Windows、Linux、macOS等多平台

安装步骤

text
git clone https://github.com/synopse/mORMot2.git
cd mORMot2
# 使用Delphi打开mORMot2.dproj
# 或使用FPC编译

实用示例

示例1:定义数据模型与ORM操作

text
unit SampleModel;

interface

uses
  mormot.core.base,
  mormot.core.data,
  mormot.orm.base,
  mormot.orm.core;

type
  // 定义客户实体
  TCustomer = class(TOrm)
  private
    FName: RawUtf8;
    FEmail: RawUtf8;
    FRegistrationDate: TDateTime;
    FActive: Boolean;
  published
    property Name: RawUtf8 read FName write FName;
    property Email: RawUtf8 read FEmail write FEmail;
    property RegistrationDate: TDateTime 
      read FRegistrationDate write FRegistrationDate;
    property Active: Boolean read FActive write FActive;
  end;

  // 定义订单实体
  TOrder = class(TOrm)
  private
    FCustomerID: TID;
    FOrderDate: TDateTime;
    FTotalAmount: Currency;
    FStatus: RawUtf8;
  published
    property CustomerID: TID read FCustomerID write FCustomerID;
    property OrderDate: TDateTime read FOrderDate write FOrderDate;
    property TotalAmount: Currency read FTotalAmount write FTotalAmount;
    property Status: RawUtf8 read FStatus write FStatus;
  end;

implementation

// 初始化数据库模型
procedure InitializeModel;
var
  Model: TOrmModel;
begin
  Model := TOrmModel.Create([TCustomer, TOrder]);
  try
    // 配置数据库连接
    // ... 数据库初始化代码
  finally
    Model.Free;
  end;
end;

end.

示例2:创建RESTful API服务

text
unit SampleService;

interface

uses
  mormot.core.base,
  mormot.rest.server,
  mormot.rest.mvc,
  mormot.orm.core,
  SampleModel;

type
  /// 客户服务接口
  ICustomerService = interface(IInvokable)
    ['{9A60C8F3-4F7A-4B8D-9E8F-1C3B6E9A7D2C}']
    
    function GetAllCustomers: TCustomerDynArray;
    function GetCustomerById(const id: TID): TCustomer;
    function CreateCustomer(const customer: TCustomer): TID;
    function UpdateCustomer(const customer: TCustomer): Boolean;
    function DeleteCustomer(const id: TID): Boolean;
    function SearchCustomers(const name: RawUtf8): TCustomerDynArray;
  end;

  /// 客户服务实现
  TCustomerService = class(TInterfacedObject, ICustomerService)
  private
    fRestServer: TRestServer;
  public
    constructor Create(aRestServer: TRestServer);
    
    function GetAllCustomers: TCustomerDynArray;
    function GetCustomerById(const id: TID): TCustomer;
    function CreateCustomer(const customer: TCustomer): TID;
    function UpdateCustomer(const customer: TCustomer): Boolean;
    function DeleteCustomer(const id: TID): Boolean;
    function SearchCustomers(const name: RawUtf8): TCustomerDynArray;
  end;

  /// MVC控制器
  TCustomerController = class(TMvcController)
  protected
    fService: ICustomerService;
  public
    constructor Create(aService: ICustomerService);
    
    [HttpGet('customers')]
    function GetCustomers: TMvcAction;
    
    [HttpGet('customers/{id}')]
    function GetCustomer(id: TID): TMvcAction;
    
    [HttpPost('customers')]
    function CreateCustomer: TMvcAction;
    
    [HttpPut('customers/{id}')]
    function UpdateCustomer(id: TID): TMvcAction;
    
    [HttpDelete('customers/{id}')]
    function DeleteCustomer(id: TID): TMvcAction;
  end;

implementation

{ TCustomerService }

constructor TCustomerService.Create(aRestServer: TRestServer);
begin
  fRestServer := aRestServer;
end;

function TCustomerService.GetAllCustomers: TCustomerDynArray;
begin
  Result := fRestServer.Orm.RetrieveList(TCustomer, '', []);
end;

function TCustomerService.GetCustomerById(const id: TID): TCustomer;
begin
  Result := TCustomer.Create;
  if not fRestServer.Orm.Retrieve(id, Result) then
    Result.Free;
end;

// ... 其他方法实现

{ TCustomerController }

constructor TCustomerController.Create(aService: ICustomerService);
begin
  fService := aService;
end;

function TCustomerController.GetCustomers: TMvcAction;
var
  customers: TCustomerDynArray;
begin
  customers := fService.GetAllCustomers;
  Result := TMvcAction.Create(customers);
end;

// ... 其他控制器方法

end.

示例3:启动HTTP服务器

text
program SampleServer;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  mormot.core.base,
  mormot.core.log,
  mormot.rest.server,
  mormot.rest.http.server,
  mormot.orm.sqlite3,
  SampleModel,
  SampleService;

var
  Model: TOrmModel;
  RestServer: TRestServer;
  HttpServer: TRestHttpServer;
  CustomerService: ICustomerService;
begin
  // 初始化日志
  TSynLog.Family.Level := LOG_VERBOSE;
  
  // 创建数据模型
  Model := TOrmModel.Create([TCustomer, TOrder]);
  
  try
    // 创建REST服务器
    RestServer := TRestServerDB.Create(Model, 'sample.db');
    
    // 注册服务
    CustomerService := TCustomerService.Create(RestServer);
    RestServer.ServiceDefine(CustomerService, [ICustomerService]);
    
    // 创建HTTP服务器
    HttpServer := TRestHttpServer.Create('8080', [RestServer]);
    HttpServer.HttpServer.KeepAliveTimeOut := 5000;
    
    // 启用CORS
    HttpServer.HttpServer.SetCors('*');
    
    WriteLn('服务器已启动,监听端口 8080');
    WriteLn('按 Enter 键停止服务器...');
    ReadLn;
    
  finally
    HttpServer.Free;
    RestServer.Free;
    Model.Free;
  end;
end.

示例4:客户端调用示例

text
unit SampleClient;

interface

uses
  mormot.core.base,
  mormot.rest.client,
  mormot.rest.http.client,
  SampleModel;

type
  TSampleClient = class
  private
    fClient: TRestHttpClient;
    fModel: TOrmModel;
  public
    constructor Create(const aServerAddress: RawUtf8);
    destructor Destroy; override;
    
    function GetCustomer(id: TID): TCustomer;
    function CreateCustomer(const name, email: RawUtf8): TID;
    function UpdateCustomerStatus(id: TID; active: Boolean): Boolean;
  end;

implementation

constructor TSampleClient.Create(const aServerAddress: RawUtf8);
begin
  fModel := TOrmModel.Create([TCustomer, TOrder]);
  fClient := TRestHttpClient.Create(aServerAddress, fModel);
end;

destructor TSampleClient.Destroy;
begin
  fClient.Free;
  fModel.Free;
  inherited;
end;

function TSampleClient.GetCustomer(id: TID): TCustomer;
begin
  Result := TCustomer.Create;
  if not fClient.CallBackGet('customers', [], id, Result) then
    Result.Free;
end;

function TSampleClient.CreateCustomer(const name, email: RawUtf8): TID;
var
  customer: TCustomer;
begin
  customer := TCustomer.Create;
  try
    customer.Name := name;
    customer.Email := email;
    customer.RegistrationDate := Now;
    customer.Active := True;
    
    Result := fClient.Add(customer, True);
  finally
    customer.Free;
  end;
end;

function TSampleClient.UpdateCustomerStatus(id: TID; active: Boolean): Boolean;
var
  customer: TCustomer;
begin
  customer := GetCustomer(id);
  if Assigned(customer) then
  try
    customer.Active := active;
    Result := fClient.Update(customer);
  finally
    customer.Free;
  end
  else
    Result := False;
end;

end.

性能优势

基准测试对比

mORMot2在多个方面表现出色:

  1. 数据库操作性能:相比传统ORM提升3-5倍

  2. JSON序列化:比标准Delphi JSON库快10倍以上

  3. HTTP服务器:支持数万并发连接

  4. 内存使用:零内存碎片设计

优化技巧

text
// 使用批量操作提升性能
procedure BatchInsertCustomers;
var
  batch: TRestBatch;
  i: Integer;
  customer: TCustomer;
begin
  batch := TRestBatch.Create(fRestServer.Orm, TCustomer, 1000);
  try
    for i := 1 to 1000 do
    begin
      customer := TCustomer.Create;
      customer.Name := FormatUtf8('Customer %', [i]);
      customer.Email := FormatUtf8('customer%@example.com', [i]);
      batch.Add(customer, True);
    end;
    batch.Send;
  finally
    batch.Free;
  end;
end;

生态系统

可用组件

  • mORMot2 Core:核心框架

  • mORMot2 SQLite3:SQLite3数据库支持

  • mORMot2 PostgreSQL:PostgreSQL支持

  • mORMot2 MongoDB:MongoDB NoSQL支持

  • mORMot2 UI:用户界面组件

工具支持

  • Swagger UI集成:自动API文档

  • 数据库迁移工具

  • 性能分析工具

  • 代码生成器

最佳实践

1. 项目结构组织

text
project/
├── src/
│   ├── models/          # 数据模型
│   ├── services/        # 业务服务
│   ├── controllers/     # MVC控制器
│   ├── repositories/    # 数据访问层
│   └── clients/         # 客户端代码
├── tests/               # 单元测试
└── docs/               # 项目文档

2. 错误处理

text
function SafeDatabaseOperation: Boolean;
begin
  try
    // 数据库操作
    Result := True;
  except
    on E: Exception do
    begin
      TSynLog.Add.Log(sllError, '数据库操作失败: %', [E.Message]);
      Result := False;
    end;
  end;
end;

3. 配置管理

text
// 使用JSON配置文件
procedure LoadConfiguration;
var
  config: TSynJsonFileSettings;
begin
  config := TSynJsonFileSettings.Create('config.json');
  try
    fDatabasePath := config.Value['database.path'];
    fServerPort := config.Value['server.port'].ToInteger;
    fLogLevel := config.Value['log.level'];
  finally
    config.Free;
  end;
end;

社区与支持

学习资源

贡献指南

  1. Fork项目仓库

  2. 创建特性分支

  3. 提交更改

  4. 创建Pull Request

  5. 遵循编码规范

总结

mORMot2代表了现代Pascal开发的先进水平,它将传统的Delphi/Free Pascal开发带入了微服务和云原生时代。通过其高性能的ORM、完整的Web服务支持和现代化的架构设计,mORMot2为Pascal开发者提供了构建企业级应用的强大工具集。

无论您是开发桌面应用、Web服务还是分布式系统,mORMot2都能提供可靠、高效的解决方案。其活跃的社区和持续的开发保证了框架的现代性和稳定性,是Pascal生态系统中不可或缺的重要项目。

mORMot2.zip
类型:压缩文件|已下载:0|下载方式:免费下载
立即下载
文章版权及转载声明

作者:icy本文地址:https://www.zelig.cn/2026/03/381.html发布于 昨天
文章转载或复制请以超链接形式并注明出处软角落-SoftNook

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏

阅读
分享

发表评论

快捷回复:

验证码

评论列表 (暂无评论,20人围观)参与讨论

还没有评论,来说两句吧...