【发布时间】:2019-10-31 14:49:36
【问题描述】:
最近我开始使用 Kotlin 在 Vert.x 中编程,这个问题对于我们使用 Vertx 工具包的任何技术都是通用的。 我创建了我的 Verticle,但其中我有业务逻辑,我想知道最佳实践是什么:
1.将逻辑分离成一个独立的类,在verticle中实例化并执行其操作,只留下verticle接收和传递消息给eventBus。
2.尽可能在同一个verticle中实现逻辑。
下面我展示了一个代码示例,但正如您所看到的,是verticle 本身的逻辑。从设计的角度来看是这样的,或者你应该把它拿出来一个独立的类,让那个verticle只用于在总线上接收和发送消息的操作
class MyAPIAgentImpl(vertx: Vertx) : CoroutineVerticle() {
var httpClient = HttpClient(vertx)
var apiConfig: JsonObject = Config.get().getJsonObject("myapi")
override suspend fun start() {
vertx.eventBus().consumer<JsonObject>(BusChannel.MY_API_CHANNEL) {
message -> launch { message.reply(findElem(message.body().getLong("Id"),
message.body().getString("countryCode"))) }
}
}
override suspend fun findElem(Id: Long, countryCode: String): String {
var hashMap = HashMap<String, String>()
hashMap.put("Accept", "*/*")
hashMap.put("Authorization", "Bearer XXXX")
val baseUrl: String = apiConfig.get("apiBaseUrl")
val port: Int = apiConfig.get("apiPort")
val apiRelativeUrl: String = apiConfig.get("apiRelativeUrl")
val resp: HttpResponse = httpClient.GET(String.format(baseUrl, countryCode), port,
String.format(apiRelativeUrl, Id), hashMap, apiConfig.getLong("requestTimeout"))
if (resp.status == HttpCode.OK) {
return resp.message.get("msg")
} else {
logger.error("[HTTP CALL] My API response with error status code: ${resp.status}")
throw ApiException(ErrorMessage(-1, resp.status, "Error calling external API"))
}
}
companion object {
private val logger = LoggerFactory.getLogger(MyAPIAgentImpl::class.java)
}
}
我想知道您在使用 Vertx 设计应用程序方面的 cmet 和经验
【问题讨论】:
-
我总是建议将业务逻辑排除在 Verticles 之外。在您决定更改框架/方法等的情况下,可以重用具有业务逻辑的方法类。
-
把所有东西放在一起直到它变得(过度)复杂是好的。突然“改变框架”的想法是世界上最不相关的事情。
标签: kotlin design-patterns vert.x