与Spring Data JPA和Feign组合映射

问题描述 投票:0回答:1

我有一个ShopMicroService,一个CustomerMicroService和一个CartMicroService。

ShopMicroService应该作为API网关工作,并且应该能够控制其他所有服务。它们与Netflix Zuul连接并路由。

我想能够打电话给localhost:8080 / list,并查看来自CustomerMicroService和CartMicroService的数据。但我也无法在ShopController中返回两个方法。我该如何解决这个问题?

Shop2CartConnector:

@FeignClient("cartmicroservice")
public interface Shop2CartConnectorRequester {

    @GetMapping("/list")
    public List<?> getCart();

Shop2CustomerConnector:

@FeignClient("customermicroservice")
public interface Shop2CustomerConnectorRequester {

    @GetMapping("/list")
    public List<?> getCustomer();

ShopController:

@ComponentScan
@RestController
public class ShopController {

    final Shop2CustomerConnectorRequester shop2CustomerConnectorRequester;
    final Shop2CartConnectorRequester shop2CartConnectorRequester;

    @Autowired
    public ShopController(Shop2CustomerConnectorRequester shop2CustomerConnectorRequester,
            Shop2CartConnectorRequester shop2CartConnectorRequester) {
        this.shop2CustomerConnectorRequester = shop2CustomerConnectorRequester;
        this.shop2CartConnectorRequester = shop2CartConnectorRequester;

    }

    @GetMapping("/getCustomer")
    public List<?> getCustomer() {
        return shop2CustomerConnectorRequester.getCustomer();

    }

    @GetMapping("/getCart")
    public List<?> getCart() {
        return shop2CartConnectorRequester.getCart();

    }

我已经尝试只调用一个方法并使用这两种方法,但它仍然只显示我返回的列表。

java spring-data-jpa netflix-eureka netflix-zuul spring-cloud-feign
1个回答
1
投票

基本上,当您进行API调用时,应用程序的request handler会将传入的HTTPS请求路由到控制器的特定处理程序方法。因此,你不能“返回两种方法”。

但是,如果我理解你正确你想要加入两个列表并将它们返回给客户端 - 如果我错了就纠正我:)为此你可以使用提供Stream API方法的concat。例如

@RestController
public class ShopController {

    final Shop2CustomerConnectorRequester shop2CustomerConnectorRequester;
    final Shop2CartConnectorRequester shop2CartConnectorRequester;

    @Autowired
    public ShopController(Shop2CustomerConnectorRequester shop2CustomerConnectorRequester,
            Shop2CartConnectorRequester shop2CartConnectorRequester) {
        this.shop2CustomerConnectorRequester = shop2CustomerConnectorRequester;
        this.shop2CartConnectorRequester = shop2CartConnectorRequester;

    }

   @GetMapping("/listAll")
   public List getAllLists() {
       List<Customer> customerList = hop2CustomerConnectorRequester.getCustomer();
       List<Cart> cartList = hop2CartConnectorRequester.getCart();

       List<?> list =  Stream.concat(customerList.stream(), cartList.stream()).collect(Collectors.toList());

       return list;
   }

但我建议使用包装器对象返回两个不同的对象类型,而不是将它们返回到单个列表中。您可能无法从列表中检索哪些对象不属于同一实现(转换等)

© www.soinside.com 2019 - 2024. All rights reserved.