伪装 QueryMap 与 POJO 的用法

Feign QueryMap usage with POJO

我在 FEIGN-README 中发现我可以做如下事情:

interface MarketDataRestClient {
    @RequestLine("GET /api/v1/depth")
    fun getOrderBook(@QueryMap orderBookQuery: OrderBookQuery) : OrderBook
}

订单簿查询:

data class OrderBookQuery(val symbol: String, val limit: Int? = 100)

Feign 应该生成查询参数:/api/v1/depth?symbol={symbol}&limit={limit}

不幸的是,我得到的是:

Exception in thread "main" java.lang.IllegalStateException: QueryMap parameter must be a Map: class OrderBookQuery
at feign.Util.checkState(Util.java:128)
at feign.Contract$BaseContract.parseAndValidateMetadata(Contract.java:126)
at feign.Contract$BaseContract.parseAndValidatateMetadata(Contract.java:64)
at feign.ReflectiveFeign$ParseHandlersByName.apply(ReflectiveFeign.java:146)
at feign.ReflectiveFeign.newInstance(ReflectiveFeign.java:53)
at feign.Feign$Builder.target(Feign.java:198)
at feign.Feign$Builder.target(Feign.java:194)

此功能将在 9.7 中可用。截至撰写此答案时,当前发布的版本是 9.6。如果您不想等待,请克隆存储库并 运行 构建项目。

只需添加一个QueryMapEncoder,如:

return Feign
        .builder()
        .client(new OkHttpClient())
        .logger(new Logger.ErrorLogger()).logLevel(Logger.Level.BASIC)
        .queryMapEncoder(new BeanQueryMapEncoder())
        .encoder(new GsonEncoder())
        .decoder(new GsonDecoder())