我正在尝试构建一个简单的应用程序,它用quarkus-rest-client调用API。我必须插入一个API密钥作为头,这对于API的所有资源都是一样的。因此,我想将这个API键(取决于环境dev/qa/prod)的值放在位于src/main/resources中的application.properties文件中。
我尝试了不同的方法来实现这个目标:
com.acme.Configuration.getKey用于@ClientHeaderParam值属性最后,我找到了下面描述的方法来使它工作。
我的问题是:有更好的方法吗?
这是我的密码:
@Path("/stores")
@RegisterRestClient
@ClientHeaderParam(name = "ApiKey", value = "{com.acme.Configuration.getStoresApiKey}")
public interface StoresService {
@GET
@Produces("application/json")
Stores getStores();
}@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();
}
}@Path("/stores")
public class StoresController {
@Inject
@RestClient
StoresService storesService;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Stores getStores() {
return storesService.getStores();
}
}发布于 2020-05-19 11:53:49
晚到派对了,但把这个放在这里供我参考。使用@ClientHeaderParam和@HeaderParam似乎有区别,因此我进一步研究了它们:根据微剖面文档,可以将值计算方法放在大括号中。该方法可以提取属性值。
有关更多示例,请参见链接。
编辑:我想出的内容与原来的类似,但在接口上使用了默认方法,因此至少可以放弃配置类。另外,使用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();发布于 2019-10-30 11:06:49
我将摆脱Configuration类,并使用@HeaderParam将配置属性从rest端点传递给rest客户端。然后,注释将此属性作为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);
}
}https://stackoverflow.com/questions/58558635
复制相似问题