介绍

  • 通过Swift服务端Vapor教材进行学习
  • 因为版本问题,学习期间会遇到各种报错,特此制作问题录,方便后续查阅!
  • 由于初学,所理解内容可能存在偏差,还望大佬可以评论指正,不胜感激

整体参考

教材【Swift服务端Vapor】中使用的都是EventLoopFuture写法
而我通过官方教材,将使用async写法

学习环境

  • Ubuntu24.04
  • docker Swift 6.1.+
  • 测试平台Apipost

过程

安装

安装主要参考官方教程
这里有必要说明几点:

  • vapor项目是通过vapor-toolbox进行创建的,所以安装vapor实际上就是安装toolbox
  • 安装toolbox需要swift环境,也就是需要先安装swift

我通过docker进行学习,所以安装使用以下命令:

1
2
3
4
5
6
7
8
9
10
11
sudo docker run -it swift:latest /bin/bash

apt update
apt install make -y

git clone https://github.com/vapor/toolbox.git
cd toolbox
# 这里的版本号可以从官仓查看最新release版本号
# https://github.com/vapor/toolbox/releases
git checkout <desired version>
make install

过关斩将

启动参数

问题说明
首先第一个遇到的就是默认vapor监听地址是127.0.0.1:8080
而该地址127.0.0.1localhost本地地址,外部无法访问,我是在linux环境中开发,所以其他设备上是无法访问到该地址的

解决方法

  • 通过nginx等反向代理工具来进行其他地址的转发,这个教程网上一堆,这里不讨论
  • 直接通过修改应用程序配置或者参数解决
    参考官方资料
    可以通过该命令指定监听地址和端口号:
    1
    2
    3
    4
    5
    6
    7
    8
    # 如果只是修改端口号,两种做法任选其一
    # 修改代码 Source/App/configure.swift 将内容添加到configure里面
    app.http.server.configuration.port = 1337
    # 直接执行命令
    swift run App serve --port 1337 # 或者简写-p

    # 如果是监听地址和端口号都需要修改,直接执行命令
    swift run App serve --bind 0.0.0.0:1337 # 或者简写为-b

存储属性检查错误

问题说明

1
error: stored property '_id' of 'Sendable'-conforming class 'Acronym' is mutable

解决方法
从网络搜集来看,这个本身应该是个warning,但不知道为什么我的是error
解决方法就是添加@unchecked Sendable参数让其不要检查即可
详情参考:On Fluent Models and Sendable warnings

docker互相访问

问题说明
因为我这里是在docker中进行vapor的开发,而数据库则是另一个docker,所以在连接数据库时,如果使用默认配置,则会报错并且挂掉

1
2
3
4
5
6
Building for debugging...
[11/11] Linking studyone
Build of product 'studyone' complete! (4.89s)
[ ERROR ] Opening new connection for pool failed: PSQLError(code: connectionError, underlying: Connection errors: SingleConnectionFailure(target: [IPv6]localhost/::1:5432, error: connection reset (error set): Connection refused (errno: 111)), SingleConnectionFailure(target: [IPv4]localhost/127.0.0.1:5432, error: connection reset (error set): Connection refused (errno: 111))) [database-id: psql]
[ WARNING ] PSQLError(code: connectionError, underlying: Connection errors: SingleConnectionFailure(target: [IPv6]localhost/::1:5432, error: connection reset (error set): Connection refused (errno: 111)), SingleConnectionFailure(target: [IPv4]localhost/127.0.0.1:5432, error: connection reset (error set): Connection refused (errno: 111)))
Swift/ErrorType.swift:254: Fatal error: Error raised at top level: PSQLError(code: connectionError, underlying: Connection errors: SingleConnectionFailure(target: [IPv6]localhost/::1:5432, error: connection reset (error set): Connection refused (errno: 111)), SingleConnectionFailure(target: [IPv4]localhost/127.0.0.1:5432, error: connection reset (error set): Connection refused (errno: 111)))

解决方法
原因是默认的配置用的是localhost,这在环境上直接开发没有问题,但是docker默认互相隔离,所以此配置需要修改为数据库的docker容器的ip地址
可以通过该命令获取

1
sudo docker inspect postgres | grep -i ipaddr

然后在configure.swift文件中修改掉对应的地址即可解决

持续更新…

问题说明

解决方法