2.19. MicroProfile REST 客户端


重要

MicroProfile REST 客户端仅作为技术预览提供。技术预览功能不包括在红帽生产服务级别协议(SLA)中,且其功能可能并不完善。因此,红帽不建议在生产环境中使用它们。这些技术预览功能可以使用户提早试用新的功能,并有机会在开发阶段提供反馈意见。

如需有关 技术预览功能支持范围 的信息,请参阅红帽客户门户网站中的技术预览功能支持范围。

JBoss EAP 7.4 支持 MicroProfile REST 客户端 1.4.x,它构建于 Jakarta RESTful Web Services 2.1 客户端 API,以提供通过 HTTP 调用 RESTful 服务的类型安全方法。MicroProfile 类型 Safe REST 客户端定义为 Java 接口。利用 MicroProfile REST 客户端,您可以使用可执行代码编写客户端应用。

MicroProfile REST 客户端启用:

  • 直观的语法
  • 供应商的程序注册
  • 供应商声明注册
  • 标头声明规格
  • 在服务器中传播标头
  • ResponseExceptionMapper
  • Jakarta 上下文和依赖注入集成

2.19.1. 直观的语法

MicroProfile REST 客户端启用分布式对象通信版本,它也在 CORBA、Java 远程方法调用(RMI)、JBoss 远程方法传递项目和 RESTEasy 中实施。例如,考虑资源:

@Path("resource")
public class TestResource {
   @Path("test")
   @GET
   String test() {
      return "test";
   }
 }

访问 TestResource 类的 Jakarta RESTful Web 服务原生方式是:

Client client = ClientBuilder.newClient();
String response = client.target("http://localhost:8081/test").request().get(String.class);

但是,Microprofile REST 客户端通过直接调用 test() 方法来支持更直观的语法:

@Path("resource")
public interface TestResourceIntf {
    @Path("test")
    @GET
    public String test();
}

TestResourceIntf service = RestClientBuilder.newBuilder()
                              .baseUrl(http://localhost:8081/))
                              .build(TestResourceIntf.class);
String s = service.test();

在上例中,让 TestResource 类的调用在使用 TestResource Intf 类时变得更容易,如调用 service.test() 所示。

以下示例是 TestResourceIntf 类的更详细版本:

@Path("resource")
public interface TestResourceIntf2 {
   @Path("test/{path}")mes("text/plain")
   @Produces("text/html")
   @POST
   public String test(@PathParam("path") String path, @QueryParam("query") String query, String entity);
}

调用 service.test("p", "q", "e") 方法会产生一个类似如下的 HTTP 消息:

POST /resource/test/p/?query=q HTTP/1.1
Accept: text/html
Content-Type: text/plain
Content-Length: 1

e

2.19.2. 供应商的程序注册

借助 MicroProfile REST 客户端,您还可以通过注册提供程序来配置客户端环境。例如:

TestResourceIntf service = RestClientBuilder.newBuilder()
                              .baseUrl(http://localhost:8081/))
                              .register(MyClientResponseFilter.class)
                              .register(MyMessageBodyReader.class)
                              .build(TestResourceIntf.class);

2.19.3. 供应商的声明注册

您还可以通过在目标接口中添加 org.eclipse.microprofile.rest.client.annotation.RegisterProvider 注解,在目标接口中添加 org.eclipse.microprofile.rest.client.annotation.RegisterProvider 注解,以声明方式注册供应商:

@Path("resource")
@RegisterProvider(MyClientResponseFilter.class)
@RegisterProvider(MyMessageBodyReader.class)
public interface TestResourceIntf2 {
   @Path("test/{path}")
   @Consumes("text/plain")
   @Produces("text/html")
   @POST
   public String test(@PathParam("path") String path, @QueryParam("query") String query, String entity);
}

使用注释 声明 MyClientResponseFilter 类和 MyMessageBodyReader 类无需调用 RestClientBuilder.register() 方法。

2.19.4. Headers 声明规格

您可以使用以下方法为 HTTP 请求指定标头:

  • 通过标注其中一个资源方法参数:
  • 声明使用 org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam 注释。

以下示例演示了设置标头,方法是使用注释 @HeaderValue 为其中一个资源方法参数添加注解:

@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
String contentLang(@HeaderParam(HttpHeaders.CONTENT_LANGUAGE) String contentLanguage, String subject);

以下示例演示了使用 org.eclipse.microprofile.rest.client.annotation.ClientHeaderParam 注释设置标头:

@POST
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.TEXT_PLAIN)
@ClientHeaderParam(name=HttpHeaders.CONTENT_LANGUAGE, value="{getLanguage}")
String contentLang(String subject);

default String getLanguage() {
   return ...;
}

2.19.5. 在服务器上传播标头

org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory 的实例如果激活,可以批量传输传入的标头到传出请求。默认实例 org.eclipse.microprofile.rest.client.ext.DefaultClientHeadersFactoryImpl 将返回一个映射,这些映射由逗号分隔的配置属性 org.eclipse.microprofile.rest.client.propagateHeaders 中列出的。以下是实例化 ClientHeadersFactory 接口的规则:

  • 在 Jakarta RESTful Web 服务请求中调用的 ClientHeadersFactory 实例必须支持注入标有 @Context 的字段和方法。
  • 由 Jakarta Contexts 和 Dependency Injection 管理的 ClientHeadersFactory 实例必须使用适当的 Jakarta Contexts 和 Dependency Injection 管理的实例。它还必须支持 @Inject 注入。

org.eclipse.microprofile.rest.client.ext.ClientHeadersFactory 接口定义如下:

public interface ClientHeadersFactory {

/**
 * Updates the HTTP headers to send to the remote service. Note that providers
 * on the outbound processing chain could further update the headers.
 *
 * @param incomingHeaders - the map of headers from the inbound Jakarta RESTful Web Services request. This will
 * be an empty map if the associated client interface is not part of a Jakarta RESTful Web Services request.
 * @param clientOutgoingHeaders - the read-only map of header parameters specified on the
 * client interface.
 * @return a map of HTTP headers to merge with the clientOutgoingHeaders to be sent to
 * the remote service.
 */
MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders,
                                      MultivaluedMap<String, String> clientOutgoingHeaders);
}

有关 ClientHeadersFactory 接口的更多信息,请参阅 ClientHeadersFactory Javadoc

2.19.6. ResponseExceptionMapper

org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper 类是 Jakarta RESTful Web Services 中定义的 javax.ws.rs.ext.ExceptionMapper 类的客户端反转。也就是说,Exception Mapper.toResponse() 方法将服务器端处理期间引发的 Exception 类转换为 Response 类,即 ResponseExceptionMapper.toThrowable() 方法将客户端上收到的 Response 类转换为 Exception 类。

您可以以编程或声明方式注册 ResponseExceptionMapper 类。如果没有注册的 ResponseExceptionMapper 类,默认的 ResponseExceptionMapper 类会将任何响应 映射到 一个 WebApplicationException 类。

2.19.7. Jakarta 上下文和依赖注入集成

在 MicroProfile REST 客户端中,您必须使用 @RegisterRestClient 类为作为 Jakarta 上下文和依赖注入 Bjection Bjection Bjection Bjection Bjection Ban 标注任何接口。例如:

@Path("resource")
@RegisterProvider(MyClientResponseFilter.class)
public static class TestResourceImpl {
      @Inject TestDataBase db;

      @Path("test/{path}")
      @Consumes("text/plain")
      @Produces("text/html")
      @POST
      public String test(@PathParam("path") String path, @QueryParam("query")
      String query, String entity) {
         return db.getByName(query);
      }
   }
   @Path("database")
   @RegisterRestClient
   public interface TestDataBase {

      @Path("")
      @POST
      public String getByName(String name);
   }

此处,MicroProfile REST 客户端实施为 TestDataBase 类服务创建一个客户端,让 TestResourceImpl 类能够轻松访问。但是,它不包括有关 TestDataBase 类实施路径的信息。此信息可以由可选 @Reg- isterProvider 参数 baseUri 提供:

@Path("database")
@RegisterRestClient(baseUri="https://localhost:8080/webapp")
public interface TestDataBase {
   @Path("")
   @POST
   public String getByName(String name);
}

这表示您可以访问 TestDataBase 的实现,地址https://localhost:8080/webapp。您还可以向外部提供以下系统变量信息:

<fully qualified name of TestDataBase>/mp-rest/url=<URL>

例如,以下命令表示您可以访问位于 https://localhost:8080/webapp 的 com.bluemondiamond.TestDatabase 类的实施:

com.bluemonkeydiamond.TestDatabase/mp-rest/url=https://localhost:8080/webapp
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat
返回顶部