mbstavola
11/08/2016, 11:50 PMfun foo(id: String): Bar? {
val query = """
SELECT * FROM a
WHERE id = ?
""".trimIndent()
return readSources(id, query, CacheTime.HOUR) { statement, key ->
statement.setNextValue(key)
val row = statement.executeQuery()
if (row.next()) {
Bar.from(row)
} else {
null
}
}
}
=======================
@Suppress("UNCHECKED_CAST")
inline fun <T> readSources(
key: String, query: String, cacheTime: Int = -1,
crossinline queryBlock: (PreparedStatementWrapper, String) -> T
): T {
return MemcachedConnection.read<T>(key) ?:
query.execute(key, queryBlock).apply {
if (cacheTime >= 0) cache(key, cacheTime)
}
}
=======================
inline fun <T> String.execute(key: String, crossinline block: (PreparedStatementWrapper, String) -> T): T {
return MySQLConnection.connection.use {
PreparedStatementWrapper(it.prepareStatement(this)).use {
block(it, key)
}
}
}