簡體   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