之前做了将SQLite作为Cache的说明,现在由于把数据全部迁移到MySQL存储因此需要把Cache也转移到MySQL作为存储媒介,由于官方没有很好的实例于仿照SQLite的流程来梳理一遍:
1 SQLite的流程
注册Provide
try services.register(FluentSQLiteProvider())
> 设置SQLite作为cacheconfig.prefer(SQLiteCache.self, for: KeyedCache.self)
2 仿照SQLite流程修改为MySQL
注册Provide
try services.register(FluentMySQLProvider())
> 设置MySQL作为Cacheconfig.prefer(MySQLDatabaseCache.self, for: KeyedCache.self)
注意:typealias MySQLDatabaseCache = DatabaseKeyedCache<ConfiguredDatabase<MySQLDatabase>>
3 通用部分
添加Cache Entity
migrations.add(model: CacheEntry<MySQLDatabase>.self, database: .mysql)
杜宇SQLite这么写Run之后没有错误而对于MySQL是无法运行的,看似如出一辙的流程为什么会有两种不同的结果呢?接下来我们就分析一下两者内部的不同
SQLite
try services.register(FluentProvider()) services.register { container -> SQLiteDatabase in let storage = try container.make(SQLiteStorage.self) return try SQLiteDatabase(storage: storage) } services.register(KeyedCache.self) { container -> SQLiteCache in let pool = try container.connectionPool(to: .sqlite) return .init(pool: pool) }
MySQL
try services.register(FluentProvider()) try services.register(MySQLProvider())
共同点都是注册了FluentProvider,不同的是SQLite设置了自身的pool作为KeyedCache,那么我们接着翻看MySQLProvider内部做了什么
MySQLProvider
try services.register(DatabaseKitProvider()) services.register(MySQLDatabaseConfig.self) services.register(MySQLDatabase.self) var databases = DatabasesConfig() databases.add(database: MySQLDatabase.self, as: .mysql) services.register(databases)
可以看到内部只是做了初始化这只一些默认
我们直接DatabaseKitProvider往里看
DatabaseKitProvider services.register(Databases.self) services.register(DatabaseConnectionCache.self) services.register(DatabaseConnectionPoolConfig.self) services.register(DatabaseConnectionPoolCache.self) // keyed cache services.register(MemoryKeyedCache(), as: KeyedCache.self) services.register(DictionaryKeyedCache.self)
终于找到了设置Cache的地方,在DatabaseKitProvider中设置MemoryKeyedCache作为KeyedCache
我们简单的翻看了整个的流程,SQLite的Provide设置的是SQLite作为cache而MySQL这边的Provider采用的是内存作为cache,那么我们怎样将MySQL切换为caceh存储容器呢?很简单仿照SQLite将MySQL的pool家加进去即可:
services.register(KeyedCache.self) { container -> MySQLDatabaseCache in let pool = try container.connectionPool(to: .mysql) return MySQLDatabaseCache.init(pool: pool ) }
更好的格式请参考:https://www.jianshu.com/p/38cee07f7779