How to access multiple resources in a single reque

2019-09-13 01:37发布

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. 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. I want to reuse the same setup if possible. Is there any way to do this. I am using jersey with spring.

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-13 02:31

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. E.g. 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.

查看更多
登录 后发表回答