简体   繁体   English

Java服务器端带注释的REST客户端库

[英]Java server side annotated REST client library

I'm building a middleware service that consumes external REST services (from the server side). 我正在构建一个使用外部REST服务(从服务器端)的中间件服务。 I'm currently using Spring boot with RestTemplate to make the remote calls. 我目前正在使用Spring Boot和RestTemplate进行远程调用。

    Map<String, String> urlVariables = new HashMap<>();
    urlVariables.put("address", IP);
    urlVariables.put("port", PORT);
    urlVariables.put("par1", parameter1);
    urlVariables.put("par2", parameter2);

    MyServiceResponse state =
            restTemplate.getForObject("http://{address}:{port}/service/{par1}/{par2}", MyServiceResponse.class, urlVariables);

I was wondering whether there's any library that provides annotations to automatically generate REST clients, like Volley does in Android. 我想知道是否有任何库提供注释来自动生成REST客户端,就像Volley在Android中一样。

@GET(url="http://{address}:{port}/service/{par1}/{par2}")
public MyServiceResponse getCurrentState(String address, String port, String par1, String par2)

There is the RESTEasy Proxy Framework : RESTEasy代理框架

Resteasy has a client proxy framework that allows you to use JAX-RS annotations to invoke on a remote HTTP resource. Resteasy的客户端代理框架使您可以使用JAX-RS批注在远程HTTP资源上调用。 The way it works is that you write a Java interface and use JAX-RS annotations on methods and the interface. 它的工作方式是编写一个Java接口,并在方法和接口上使用JAX-RS批注。

Are you looking for something like this?: 您是否正在寻找这样的东西?

https://github.com/dpalmisano/NoTube-Beancounter-2.0/blob/master/platform/src/main/java/io/beancounter/platform/rai/MyRaiTVService.java#L45 https://github.com/dpalmisano/NoTube-Beancounter-2.0/blob/master/platform/src/main/java/io/beancounter/platform/rai/MyRaiTVService.java#L45

@POST
@Path("/login/auth")
public Response loginWithAuth(
        @FormParam("username") String username,
        @FormParam("token") String token

) {
    try {
        Validations.checkNotEmpty(username, "Missing username parameter");
        Validations.checkNotEmpty(token, "Missing MyRaiTV token parameter");
    } catch (Exception ex) {
        return error(ex.getMessage());
    }

You can use REST Gap for this. 您可以为此使用REST Gap You only need to: 您只需要:

  • Have Spring MVC or JAX-RS style annotated interfaces 具有Spring MVC或JAX-RS样式的带注释的接口
  • Call the REST Gap factory and pass your interface and a RestTemplate instance 调用REST Gap工厂并传递您的界面和RestTemplate实例
  • Receive an implementation of your interface that calls your REST Service 接收调用REST服务的接口的实现

This is how it looks in code (for a Spring-MVC interface IPetStoreService): 这是它在代码中的外观(对于Spring-MVC接口IPetStoreService):

// Create client
IPetStoreService client = RESTTemplateSpringMVCFactory
    .create(restTemplate, "http://mypetstore.com/rest", IPetStoreService.class);

// Call it!
List<Pet> pets = client.listPets();

That's it! 而已!

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

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