如何解决从普通函数异步返回值
我正在使用Bukkit API开发Minecraft插件。我使用的侦听器要求从数据库中(异步)检索数据,然后检查该数据并执行其他操作。
异步访问任何Bukkit API方法不是一个好主意。
我的活动看起来像这样
class ClickSignEvent(private val plugin: ExpBankPlugin,private val connection: Connection): Listener {
@EventHandler(ignoreCancelled = true)
fun onClickSign(event: PlayerInteractEvent) {
// get a few things sync like their UUID
val results = getAmount(uuid,world,clickedBlock) // this needs to be accessed async
// do a few things sync based on the results val
}
private suspend fun getAmount(uuid: UUID,world: String,clickedBlock: Block): ResultSet? {
return withContext(Dispatchers.IO) {
return@withContext try {
val query = "SELECT amount,rowid FROM expbank_expbanks WHERE uuid=? and world=? and x=? and y=? and z=?"
val preparedStatement = connection.prepareStatement(query)
preparedStatement.setString(1,uuid.toString())
preparedStatement.setString(2,world)
preparedStatement.setInt(3,clickedBlock.x)
preparedStatement.setInt(4,clickedBlock.y)
preparedStatement.setInt(5,clickedBlock.z)
preparedStatement.executeQuery()
} catch (e: SQLException) {
e.printStackTrace()
null
}
}
}
这是我的数据库类:
class ExpDataSource {
private var ds: HikariDataSource
val connection: Connection
get() = ds.connection
init {
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance()
val config = HikariConfig()
config.jdbcUrl = "jdbc:mysql://ip:3306/u1770_db?useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"
config.username = "u1770"
config.password = "password"
config.driverClassName = "com.drugpvp.expbank.shadow.mysql.cj.jdbc.Driver"
config.addDataSourceProperty("cachePrepStmts","true")
config.addDataSourceProperty("prepStmtCacheSize","256")
config.addDataSourceProperty("prepStmtCacheSqlLimit","2048")
config.addDataSourceProperty("maximumPoolSize","10")
config.addDataSourceProperty("minimumIdle","2")
ds = HikariDataSource(config)
}
fun createTable() {
val statement = connection.createStatement()
val query = "CREATE TABLE IF NOT EXISTS expbank_expbanks (rowid INTEGER AUTO_INCREMENT PRIMARY KEY,uuid VARCHAR(36),world TEXT,amount INTEGER,X INTEGER,Y INTEGER,Z INTEGER)"
statement.executeUpdate(query)
}
}
我想不出要做什么以使某些事情同步,等待结果异步,然后基于此做一些同步事情-而不会阻塞主线程。在getAmount()
上说“仅应从协程或其他暂停函数调用暂停函数'getAmount'”
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com(将#修改为@)