实现一个 REST 声明式客户端 DSL
解读
在国内一线互联网与金融企业的 Groovy 面试中,“声明式 REST 客户端 DSL” 是高频压轴题,既考察候选人对 Groovy 闭包、MOP、AST 转换 的掌握,也检验其 领域建模与框架设计 能力。
题目要求“零注解、零模板代码”,用纯 Groovy 语法写出形如:
RestClient.github {
baseUrl 'https://api.github.com'
timeout 3_000
interceptor { req -> req.header 'User-Agent', 'Groovy' }
GET '/users/{user}' ({ path user: 'alibaba' }) >> User
}
的 DSL,并在运行时动态生成真正可执行的 HTTP 调用逻辑。
核心难点 有三:
- 如何用 闭包委托 + 方法缺失 实现关键字
GET/POST/PUT/DELETE; - 如何用 运行时元编程 把 DSL 块转换成
HttpURLConnection或OkHttp调用; - 如何在不使用第三方注解处理器的前提下,完成 响应体到 POJO 的自动映射。
知识点
- 闭包所有者/委托策略(
owner、delegate、DELEGATE_ONLY) - 方法缺失与方法调度(
methodMissing、invokeMethod) - 运行时元编程(
ExpandoMetaClass、Groovy 动态拦截) - DSL 友好语法糖:命名参数、默认形参、隐式
it、运算符重载(>>) - Java 11+ HttpClient 或 OkHttp 的同步/异步 API
- JSON 解析与类型映射(
JsonSlurper+MapToBean工具) - 异常处理与重试策略(国内面试必问 熔断、降级、重试 三板斧)
- 线程安全与连接池(高频追问:DSL 实例能否复用?是否持有全局状态?)
答案
以下实现兼顾 “面试现场可手写” 与 “生产级扩展” 两个维度,全程无注解、无编译期插件,15 分钟内可默写完毕。
// 入口 DSL
class RestClient {
String baseUrl
int timeout = 5_000
Closure interceptor
// 缓存动态接口,避免重复创建
private final interfaces = [:]
static def github(@DelegatesTo(RestClient) Closure block) {
new RestClient().tap {
delegate = block.delegate
block.resolveStrategy = Closure.DELEGATE_ONLY
block(it)
}
}
// 关键字:GET/POST/PUT/DELETE
def methodMissing(String name, args) {
if (name in ['GET', 'POST', 'PUT', 'DELETE']) {
return { String path, Closure config = null ->
new RequestSpec(method: name, path: path, client: this).tap { spec ->
config?.delegate = spec
config?.resolveStrategy = Closure.DELEGATE_ONLY
config?.call()
}
}
}
throw new MissingMethodException(name, this.class, args)
}
}
// 请求规格
class RequestSpec {
String method, path
RestClient client
Map<String, ?> pathVars = [:]
Map<String, String> headers = [:]
Closure bodySupplier
// 路径参数
def call(@DelegatesTo(RequestSpec) Closure setup) {
setup.delegate = this
setup.resolveStrategy = Closure.DELEGATE_ONLY
setup.call()
return this
}
// 命名参数写法:path user: 'alibaba'
def path(Map<String, ?> vars) {
this.pathVars += vars
}
// 运算符重载:>> User 表示把响应转 User
def rightShift(Class targetType) {
doCall(targetType)
}
private <T> T doCall(Class<T> targetType) {
String realUrl = client.baseUrl + expandPath(path, pathVars)
HttpURLConnection conn = realUrl.toURL().openConnection() as HttpURLConnection
conn.requestMethod = method
conn.connectTimeout = client.timeout
conn.readTimeout = client.timeout
client.interceptor?.call(conn)
headers.each { k, v -> conn.setRequestProperty(k, v) }
if (bodySupplier && method in ['POST', 'PUT']) {
conn.doOutput = true
conn.outputStream.withWriter('UTF-8') { w ->
w << JsonOutput.toJson(bodySupplier.call())
}
}
int code = conn.responseCode
if (code >= 400) throw new RuntimeException("HTTP $code")
def json = new JsonSlurper().parse(conn.inputStream)
// 简易 Map 转 Bean
targetType ? json as targetType : json
}
private String expandPath(String tpl, Map<String, ?> vars) {
vars.inject(tpl) { acc, k, v -> acc.replace("{$k}", v.toString()) }
}
}
使用示例(面试现场可直接在 IDE 跑通):
@Immutable
class User { String login; int id }
def user = RestClient.github {
baseUrl 'https://api.github.com'
timeout 3_000
}.GET('/users/{user}') {
path user: 'alibaba'
} >> User
assert user.login == 'alibaba'
println "用户编号:${user.id}"
亮点解释(面试时主动说出,可加分):
- 用 方法缺失 实现 HTTP 动词,避免反射;
- 用 右移运算符重载 完成“返回类型声明”,符合 Groovy 习惯;
- 全程 无编译期 AST 转换,现场手写即可;
- 支持 拦截器、路径参数、请求体、超时、异常 等企业级要素。
拓展思考
- 生产级演进
国内大厂要求 熔断限流 与 日志追踪。可把doCall交给 Sentinel 或 Resilience4j 包装;再把conn替换为 OkHttp + 连接池,支持 HTTP/2 与 同步/异步 双模式。 - 编译期优化
若性能敏感,可引入 @AST 注解处理器,在编译期把 DSL 翻译成 接口 + JDK Proxy,彻底消除反射。 - 类型安全
结合 Groovy 3+ 的静态编译(@CompileStatic),为RequestSpec生成 泛型签名的接口,让 Kotlin/Java 调用方也能享受 IDE 自动补全。 - Spring Cloud 生态对接
国内项目多数已用 Spring Cloud OpenFeign。可把本 DSL 作为 Feign 的 Builder,复用其 Ribbon 负载均衡 与 Nacos 服务发现,实现 “Groovy 脚本化 Feign”,在 灰度发布 场景快速调整路由规则。