繁体   English   中英

Quarkus & Microprofile:有没有更好的方法将 application.properties 中的属性用于@ClientHeaderParam?

[英]Quarkus & Microprofile : Is there a better way to use a property from application.properties into @ClientHeaderParam?

我正在尝试构建一个简单的应用程序,该应用程序使用quarkus-rest-client调用 API 。 我必须注入一个 API 密钥作为 header,这对于 API 的所有资源都是相同的。 所以我想把这个 API 密钥的值(取决于环境dev/qa/prod )放在位于src/main/resourcesapplication.properties文件中。

我尝试了不同的方法来实现这一点:

  • 直接使用com.acme.Configuration.getKey@ClientHeaderParam值属性
  • 创建一个 StoresClientHeadersFactory class 实现 ClientHeadersFactory 接口注入配置

最后,我找到了下面描述的方法来使它工作。

我的问题是:有没有更好的方法呢?

这是我的代码:

  • StoreService.java这是我到达 API 的客户
@Path("/stores")
@RegisterRestClient
@ClientHeaderParam(name = "ApiKey", value = "{com.acme.Configuration.getStoresApiKey}")
public interface StoresService {

    @GET
    @Produces("application/json")
    Stores getStores();

}
  • 配置.java
@ApplicationScoped
public class Configuration {

    @ConfigProperty(name = "apiKey.stores")
    private String storesApiKey;

    public String getKey() {
        return storesApiKey;
    }

    public static String getStoresApiKey() {
        return CDI.current().select(Configuration.class).get().getKey();
    }

}
  • StoresController.java即 REST controller
@Path("/stores")
public class StoresController {

    @Inject
    @RestClient
    StoresService storesService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Stores getStores() {
        return storesService.getStores();
    }

}

聚会迟到了,但把它放在这里供我自己参考。 使用@ClientHeaderParam 和@HeaderParam 似乎有区别,所以我进一步调查了一点:根据Microprofile docs ,您可以将计算方法放在花括号中的值。 该方法可以提取属性值。

有关更多示例,请参见链接。

编辑:我想出的类似于原始的,但在界面上使用默认方法,因此您至少可以丢弃配置 class。 此外,使用 org.eclipse.microprofile.config.Config 和 ConfigProvider 类来获取配置值:

@RegisterRestClient
@ClientHeaderParam(name = "Authorization", value = "{getAuthorizationHeader}")
public interface StoresService {

    default String getAuthorizationHeader(){
        final Config config = ConfigProvider.getConfig();
        return config.getValue("apiKey.stores", String.class);
    }

    @GET
    @Produces("application/json")
    Stores getStores();

我将摆脱Configuration class 并使用@HeaderParam将您的配置属性从您的 rest 端点传递到您的 rest 客户端。 然后,注释会将此属性作为 HTTP header 发送到远程服务。

像这样的东西应该有效:

@Path("/stores")
@RegisterRestClient
public interface StoresService {

    @GET
    @Produces("application/json")
    Stores getStores(@HeaderParam("ApiKey") storesApiKey);

}

@Path("/stores")
public class StoresController {
    @ConfigProperty(name = "apiKey.stores")
    private String storesApiKey;

    @Inject
    @RestClient
    StoresService storesService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public Stores getStores() {
        return storesService.getStores(storesApiKey);
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM