美文网首页DartWeb
Dart-Aqueduct框架开发(三)

Dart-Aqueduct框架开发(三)

作者: rhyme_lph | 来源:发表于2019-09-14 18:43 被阅读0次

    上一篇

    声明:本文首发于微信订阅号:Dart客栈,微信后台回复05163获取本篇源码
    文章为原创,如需转载请注明出处,并告知作者,谢谢!

    简介

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

    1. 添加配置文件

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

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

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

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

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

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

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

    class DemoChannel extends ApplicationChannel {
      @override
      Future prepare() async {
    //new
        final AppConfig _config=AppConfig(options.configurationFilePath);
        options.port=_config.port;
    //new
      }
    }
    

    然后启动你的服务器即可

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

    2.PostgreSQL数据库

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

    PostgreSQL介绍

    PostgreSQl安装

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

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

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

    PostgreSQl初始化

    • 查看当前版本pg_ctl -V
    rhymes-MacBook-Air:~ rhyme$ pg_ctl -V
    pg_ctl (PostgreSQL) 11.5
    
    • 启动服务brew services start postgresql
    rhymes-MacBook-Air:~ rhyme$ brew services start postgresql
    ==> Successfully started `postgresql` (label: homebrew.mxcl.postgresql)
    
    • 卸载PostgreSqlbrew uninstall postgres
    • 添加用户createuser --interactive
    rhymes-MacBook-Air:~ rhyme$ createuser --interactive
    Enter name of role to add: rhymelph
    Shall the new role be a superuser? (y/n) y
    
    • 修改密码
    rhymes-MacBook-Air:~ rhyme$ psql postgres
    psql (11.5)
    Type "help" for help.
    postgres=# \password rhymelph
    Enter new password: 
    Enter it again: 
    

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

    • 新建一个连接


      image.png
    • 新建数据库


      image.png

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

    3.项目连接数据库

    • config.yaml文件下添加
    database:
      host: localhost
      port: 5432
      databaseName: "my_data"
      username: "rhymelph"
      password: "123456"
    
    • app_config.dart文件下添加下面代码
    import 'demo.dart';
    
    class AppConfig extends Configuration{
      AppConfig(String path):super.fromFile(File(path));
      int port;
    //new
      DatabaseConfiguration database;
    //new
    }
    
    • channel.dart文件夹下生成实例
    class DemoChannel extends ApplicationChannel {
      ManagedContext context;//可通过该实例操作数据库
    
      @override
      Future prepare() async {
        //执行初始化任务的方法
        final AppConfig _config = AppConfig(options.configurationFilePath);
        options.port = _config.port;
    //new
        final dataModel = ManagedDataModel.fromCurrentMirrorSystem();//描述应用程序的数据模型
        final psc = PostgreSQLPersistentStore.fromConnectionInfo(
            _config.database.username,
            _config.database.password,
            _config.database.host,
            _config.database.port,
            _config.database.databaseName);//管理与单个数据库的连接
        context=ManagedContext(dataModel, psc);
    //new
      }
    }
    

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

    4.将实体类映射到表

    • 运行命令aqueduct db generate 初始化迁移文件,运行后,会在项目下生成一个版本迁移文件
      image.png
    • 运行命令aqueduct db upgrade --connect postgres://rhymelph:123456@localhost:5432/my_data将版本迁移文件同步到你的数据库
    • 你也可以在项目根目录下新建一个database.yaml文件,然后存放数据库信息,下次只要运行aqueduct db upgrade即可
    username: "rhymelph"
    password: "123456"
    host: "localhost"
    port: 5432
    databaseName: "my_data"
    
    • 新建一个Article类,添加下面内容
    import '../demo.dart';
    
    class Article extends ManagedObject<_Article> implements _Article {}
    
    class _Article {
      @primaryKey//作为主键 == @
      int id;
    
      String content;//内容
    
      @Column(indexed: true)//添加索引
      DateTime createData;
    }
    

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

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

    5.使用接口查询数据库

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

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

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

    image.png

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

    下一篇

    相关文章

      网友评论

        本文标题:Dart-Aqueduct框架开发(三)

        本文链接:https://www.haomeiwen.com/subject/qeluyctx.html