简体   繁体   English

如何在单个请求中访问多个资源

[英]How to access multiple resources in a single request : Jersey Rest

I am trying to a find a good design for the following scenario. 我正在尝试为以下情况找到一个好的设计。 I have a POST rest service which will be given an array of services as data. 我有一个POST rest服务,该服务将作为数据提供一系列服务。 And which should in turn be calling them one by one to aggregate results on the server and send them back to the client. 然后依次调用它们,以在服务器上汇总结果并将其发送回客户端。

@Path("/resource1") @Path("/resource2") @Path("/collection")

Post data to /collection {["serviceName": "resource1", "data":"test1"], ["serviceName":"resource2","data":"test2"]}

The reason i need the resource1 and resource2 are, because those services can be called standalone also. 我之所以需要resource1和resource2是因为这些服务也可以称为独立服务。 I want to reuse the same setup if possible. 如果可能,我想重用相同的设置。 Is there any way to do this. 有什么办法可以做到这一点。 I am using jersey with spring. 我春天用球衣。

Not sure what these resources have in common. 不知道这些资源有什么共同点。 If the post method has the same signature for all of them, you could have an abstract class or interface they implement defining the post method and can try using ResourceContext.matchResource to do this. 如果post方法对所有对象都具有相同的签名,则可以让它们实现定义post方法的抽象类或接口,并可以尝试使用ResourceContext.matchResource做到这一点。 Eg something like this: 例如这样的事情:

public abstract class AbstractResource {
    public abstract String post(Object data);
}

@Path("/resource1")
public class Resource1 extends AbstractResource {
    @POST
    public String post(String data) {
        // do something
    }
}

@Path("/collection")
public class CollectionResource {
    @Context
    private ResourceContext rc;

    @POST
    @Consumes("application/json")
    public String post(List<PostRequest> postRequests) {
        StringBuilder result = new StringBuilder();
        for (PostRequest pr : postRequests) {
            // should wrap this in try-catch
            AbstractResource ar = rc.matchResource(pr.resource,
                    AbstractResource.class);
            sb.append(ar.post(pr.data));
        }
        return result.toString();
    }
}

@XmlRootElement
public class PostRequest {
    public String resource;
    public String data;
}

Hopefully you got the idea and will be able to play with it and tweak it to fit your needs. 希望您有这个主意,并且能够进行尝试并对其进行调整以满足您的需求。

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

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