Dart-Aqueduct框架开发(三)

1,198 阅读4分钟

微信公众号:Dart客栈关注可了解更多关于Dart的教程和技术文章;

简介

这篇文章将学习如何设置配置文件,连接PostgreSQL数据库

1. 添加配置文件

我们可以在main.dart中找到 option.configurationFilePath,它的值对应为配置文件的路径,默认以项目为根路径

 1import 'package:demo/demo.dart'; 2 3Future main() async { 4  final app = Application<DemoChannel>() 5//watch 6      ..options.configurationFilePath = "config.yaml"//载入配置文件 7//watch 8      ..options.port = 8888;//端口号 910  final count = Platform.numberOfProcessors ~/ 2;//启动的isolate数量11  await app.start(numberOfInstances: count > 0 ? count : 1);//应用启动1213  print("Application started on port: ${app.options.port}.");14  print("Use Ctrl-C (SIGINT) to stop running the application.");15}

可以看到配置文件为项目文件夹下面的config.yaml

可以看到当前还没有相关的配置信息,所以我们可以添加下面的配置
1port: 8080

把我们的端口号设置为 8080,然后在lib文件夹下面新建一个 AppConfig类,代码如下:

1import 'demo.dart';23class AppConfig extends Configuration{45  AppConfig(String path):super.fromFile(File(path));67  int port;89}

channel.dart文件下添加你的配置实例,即可应用到项目中,代码如下

1class DemoChannel extends ApplicationChannel {2  @override3  Future prepare() async {4//new5    final AppConfig _config=AppConfig(options.configurationFilePath);6    options.port=_config.port;7//new8  }9}

然后启动你的服务器即可

这里有个bug,就是打印的 Port: 8888这个是错的,我们的端口已经更改为8080,所以已经访问不了 8888端口,我们请求一下上一节的接口,把端口改为8080,http://localhost:8080/hello
可看到我们成功的访问

2.PostgreSQL数据库

很多小伙伴们比较少用到这个PostgreSQL这个数据库,一般用的 SQL ServerMy SQL等等,小编当年读大学的时候也学的是 SQL Server,那么为什么要使用PostgreSQL这个数据库呢

PostgreSQL介绍

  • PostgreSQL是自由的对象-关系型数据库服务器(数据库管理系统),在BSD许可证下发行。-- 维基百科

  • The World's Most Advanced Open Source Relational Database(世界上最先进的开源关系数据库)

  • 可以在知乎上找到答案https://www.zhihu.com/question/20010554

PostgreSQl安装

打开官网https://www.postgresql.org/点击Download,找到你系统对应的版本,我对应的是 macos

然后点击Download the installer即可
然后进入下载
当然,你也可以使用brew工具进行安装,输入下面命令即可:
1brew install postgresql

安装成功后,可以到/usr/local/var/postgres这个路径查看

PostgreSQl初始化

  • 查看当前版本pg_ctl -V

1rhymes-MacBook-Air:~ rhyme$ pg_ctl -V2pg_ctl (PostgreSQL) 11.5
  • 启动服务brew services start postgresql

1rhymes-MacBook-Air:~ rhyme$ brew services start postgresql2==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
  • 卸载PostgreSqlbrew uninstall postgres

  • 添加用户createuser --interactive

1rhymes-MacBook-Air:~ rhyme$ createuser --interactive2Enter name of role to add: rhymelph3Shall the new role be a superuser? (y/n) y
  • 修改密码

1rhymes-MacBook-Air:~ rhyme$ psql postgres2psql (11.5)3Type "help" for help.4postgres=# \password rhymelph5Enter new password: 6Enter it again: 

使用数据库可视化工具Navicat Premium

  • 新建一个连接

  • 新建数据库

好了,我们已经有了账号,密码,数据库了,下面我们来把项目连接上数据库

3.项目连接数据库

  • config.yaml文件下添加

1database:2  host: localhost3  port: 54324  databaseName: "my_data"5  username: "rhymelph"6  password: "123456"
  • app_config.dart文件下添加下面代码

1import 'demo.dart';23class AppConfig extends Configuration{4  AppConfig(String path):super.fromFile(File(path));5  int port;6//new7  DatabaseConfiguration database;8//new9}
  • channel.dart文件夹下生成实例

 1class DemoChannel extends ApplicationChannel { 2  ManagedContext context;//可通过该实例操作数据库 3 4  @override 5  Future prepare() async { 6    //执行初始化任务的方法 7    final AppConfig _config = AppConfig(options.configurationFilePath); 8    options.port = _config.port; 9//new10    final dataModel = ManagedDataModel.fromCurrentMirrorSystem();//描述应用程序的数据模型11    final psc = PostgreSQLPersistentStore.fromConnectionInfo(12        _config.database.username,13        _config.database.password,14        _config.database.host,15        _config.database.port,16        _config.database.databaseName);//管理与单个数据库的连接17    context=ManagedContext(dataModel, psc);18//new19  }20}

到此,我们已经可以使用数据库了,但Aqueduct为我们准备了 实体类映射到表的功能

4.将实体类映射到表

  • 运行命令aqueduct db generate 初始化迁移文件,运行后,会在项目下生成一个版本迁移文件

  • 运行命令aqueduct db upgrade --connect postgres://rhymelph:123456@localhost:5432/my_data将版本迁移文件同步到你的数据库

  • 你也可以在项目根目录下新建一个database.yaml文件,然后存放数据库信息,下次只要运行 aqueduct db upgrade即可

1username: "rhymelph"2password: "123456"3host: "localhost"4port: 54325databaseName: "my_data"
  • 新建一个Article类,添加下面内容

 1import '../demo.dart'; 2 3class Article extends ManagedObject<_Article> implements _Article {} 4 5class _Article { 6  @primaryKey//作为主键 == @ 7  int id; 8 9  String content;//内容1011  @Column(indexed: true)//添加索引12  DateTime createData;13}

然后使用aqueduct db generateaqueduct db upgrade即可将实体类字段同步到数据库中(这里需要注意,这个实体类必须导入到channel.dart文件中才有效)

可以看到我们成功的执行了根据实体类在数据库生成对应的表,如果小伙伴也执行成功,会看到下面的两张表
一张表_article为我们要生成的表,另一张为Aqueduct框架记录版本号使用的,为自动生成,我们暂时不用管

5.使用接口查询数据库

接下来我们在表中添加一条数据,然后添加下面代码到channel.dart

 1  @override 2  Controller get entryPoint { 3    //定义路由、请求链接等,在启动期间调用 4    //... 5//new 6    router.route('/queryAllArticle').linkFunction((request) async{ 7      final query = Query<Article>(context);//拿到表的查询实例 8      final List<Article> articles=await query.fetch();//查询所有数据 9      return Response.ok(articles);//数据以json形式返回给客户端10    });11//new12    return router;13  }

可以看到,Aqueduct使用ORM对象关系映射,免去了使用 SQL语句的麻烦,十分便捷,然后我们启动服务器,访问接口http://localhost:8080/queryAllArticle

当看到请求成功,并显示我们在存储在数据库中的数据时,👏恭喜你,成功的使用接口查询数据库!这一节的学习就到这里了,希望帮忙转发,让更多的小伙伴学习到这个语言和框架