micronaut - 创建多个具有相同接口的 HTTP 客户端
问题描述
我们需要能够连接到多个 Elasticsearch 服务器。我们有一个简单的 Elasticsearch 客户端,使用 Micronaut 的声明式方法进行定义。
但是,作为多租户环境,我们需要能够定义许多这样的客户端。这些客户端中的每一个显然都有不同的 URL,并且需要使用不同的 HTTPFilter 进行身份验证。
Micronaut 是一个以编译时为重点的框架,我如何动态创建许多由配置选项定义的此类 bean?
更新:
我看到@Factory
结合@EachBean
注释可能是一种有前途的方法,但声明性 HTTP 客户端是一个接口,而不是一个具体的类。如何仅基于接口实例化这样的客户端?
请参阅https://docs.micronaut.io/latest/guide/index.html#eachBean
解决方案
通常创建您的声明性@Client 接口,除了 2 个细节:
- 使其指向本地的网址“/proxy-elastic”
- 向每个声明的方法添加一个 @Header("X-Elastic-Cluster") 字符串集群
@Client("/proxy-elastic")
public interface DeclarativeHttpClient {
@Get("/connectors/{name}")
void diplay(@Header(value = "X-Elastic-Cluster") String cluster, String name);
}
然后,创建一个 ProxyFilter 并根据 Header 值改变 HttpRequest ( https://docs.micronaut.io/latest/guide/index.html#proxyClient )
@Filter("/proxy-elastic/**")
public class KafkaConnectClientProxy extends OncePerRequestHttpServerFilter {
@Inject
ProxyHttpClient client;
@Override
protected Publisher<MutableHttpResponse<?>> doFilterOnce(HttpRequest<?> request, ServerFilterChain chain) {
// retrieve the config for this cluster
String cluster = request.getHeaders().get("X-Elastic-Cluster");
var config = getConfigForCluster(cluster);
URI newURI = URI.create(config.url);
// call kafka connect with proper URL and Auth
return Publishers.map(client.proxy(
request.mutate()
.uri(b -> b
.scheme(newURI.getScheme())
.host(newURI.getHost())
.port(newURI.getPort())
.replacePath(StringUtils.prependUri(
newURI.getPath(),
request.getPath().substring("/proxy-elastic".length())
))
)
.basicAuth(config.basicAuthUsername, config.basicAuthPassword)
), response -> response.header("X-My-Response-Header", "YYY"));
}
}
推荐阅读
- asp.net - 如何在 ASP.Net Core 2.0 应用程序中使用 Bootstrap?
- python-3.x - Python3.6:使用import os、iter、next打印同名文件目录
- python - 动态改变 raw_input 的消息
- node.js - 在 ExpressJS 中打印会话对象
- r - 如何在r中的列表上制作列联表
- postgresql - 使用 PostgreSQL 进行关键字搜索
- java - 从动态创建的 JTextField 中获取值
- wpf - 以编程方式设置时,讲述人不读取复选框状态
- json - Angular 5.2.10 - TypeScript 2.4.2 属性访问器 json 映射
- c# - C# EF6 映射未应用于选择