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

Tat*_*ute 5 java client microprofile quarkus

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

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

  • 直接使用com.acme.Configuration.getKey@ClientHeaderParamvalue 属性
  • 创建一个 StoresClientHeadersFactory 类,该类实现 ClientHeadersFactory 接口以注入配置

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

我的问题是:有没有更好的方法来做到这一点?

这是我的代码:

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

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

}
Run Code Online (Sandbox Code Playgroud)
  • 配置文件
@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();
    }

}
Run Code Online (Sandbox Code Playgroud)
  • StoresController.java是 REST 控制器
@Path("/stores")
public class StoresController {

    @Inject
    @RestClient
    StoresService storesService;

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

}
Run Code Online (Sandbox Code Playgroud)

Sør*_*sen 7

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

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

编辑:我想出的与原来的相似,但在界面上使用了默认方法,因此您至少可以放弃 Configuration 类。此外,使用 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();

Run Code Online (Sandbox Code Playgroud)


loi*_*ieu 4

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

像这样的东西应该有效:

@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);
    }

}
Run Code Online (Sandbox Code Playgroud)