最经几天一直在拜读Vapor中service的源码,连续几天上班途中和下班之后都是在翻看源码,从刚开始感觉云山雾绕到逐渐清晰
server内部介绍
而最终内部的所有被注册的server都会通过下面来进行实例化注册到系统中来使用
被注册service最终实例化
看了这么久我们根据最新发送邮件的需求自己写个service,在此我们通过Provider来实现IBM swift SMTP
在此我们分为SKSmtpProvider和SKSmtpConfig两部分,其中SKSmtpConfig为SMTP的信息配置项而SKSmtpProvider为真实的Server实现部分
先上Provider的代码
class SKSmtpProvider: Provider {
func register(_ services: inout Services) throws {
services.register { (container) -> SKSmtp in
let config = try container.make(SKSmtpConfig.self)
assert(config != nil, "选注册SKSmtpConfig实例,才能使用SKSmtp")
return SKSmtp.init(config: config)
}
}
func didBoot(_ container: Container) throws -> EventLoopFuture<Void> {
let result = container.eventLoop.newPromise(Void.self)
result.succeed()
return result.futureResult
}
}
对于使用Provider来实现service则必须实现Provider 协议
然后是我们SMTP的server实现,对于service协议,就只是一个类型声明:
public protocol Service {}
class SKSmtp : Service {
fileprivate var smtp: SMTP?
init(config: SKSmtpConfig) {
self.smtp = SMTP.init(hostname: config.hostname, email: config.email, password: config.password, port: config.port, useTLS: config.useTLS, tlsConfiguration: config.tlsConfiguration, authMethods:config.authMethods, domainName: config.domainName, timeout: config.timeout)
}
/// Send an email.
///
/// - Parameters:
/// - mail: `Mail` object to send.
/// - completion: Callback when sending finishes. `Error` is nil on success. (optional)
public func send(_ mail: Mail, completion: ((Error?) -> Void)? = nil) {
smtp?.send(mail, completion: completion)
}
public func send(_ mails: [Mail],
progress: Progress = nil,
completion: Completion = nil) {
smtp?.send(mails, progress: progress, completion: completion)
}
}
最后是Config,很简单Config其实就是SMTP的配置信息
public struct SKSmtpConfig : Service{
var hostname: String
var email: String
var password: String
var port: Int32 = 465
var useTLS: Bool = false
var tlsConfiguration: SwiftSMTP.TLSConfiguration?
var authMethods:[ AuthMethod] = []
var domainName: String = "localhost"
var timeout: UInt = 10
init(hostname: String, email: String, password: String, port: Int32 = 465, useTLS:Bool = false,tlsConfiguration:SwiftSMTP.TLSConfiguration? = nil, authMethods:[ AuthMethod] = [], domainName: String = "localhost", timeout: UInt = 10) {
self.hostname = hostname
self.email = email
self.password = password
self.port = port
self.useTLS = useTLS
self.tlsConfiguration = tlsConfiguration
self.domainName = domainName
self.timeout = timeout
}
}
所有的都已经实现了,接下来就是使用了
1 系统的configure中注册对应的Provider
let smtpConfig = SKSmtpConfig.init(hostname: "", email: "", password: "")
services.register(smtpConfig)
try services.register(SKSmtpProvider())
2 在网络请求中实现
public func regist(req: Request)throws-> EventLoopFuture<String>{
let smtp: SKSmtp = try req.make(SKSmtp.self)
smtp.send(<#T##mail: Mail##Mail#>, completion: <#T##((Error?) -> Void)?##((Error?) -> Void)?##(Error?) -> Void#>)
Vapor集成使用
.package(url: "https://github.com/skeyboy/SKSmtp.git", from:"0.0.1")
网友评论