package com.imooc.product.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class ServerController { @GetMapping("/msg") public String msg() { return "this is product' msg"; } }
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-feign</artifactId> </dependency>
package com.imooc.order; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } }
package com.imooc.order.client; import com.imooc.order.dataobject.ProductInfo; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import java.util.List; @FeignClient(name = "product") public interface ProductClient { @GetMapping("/msg") String productMsg(); @PostMapping("/product/listForOrder") List<ProductInfo> listForOrder(@RequestBody List<String> productIdList); }
package com.imooc.order.controller; import com.imooc.order.client.ProductClient; import com.imooc.order.dataobject.ProductInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Arrays; import java.util.List; @RestController @Slf4j public class ClientController { @Autowired private ProductClient productClient; @GetMapping("/getProductMsg") public String getProductMsg() { String response = productClient.productMsg(); log.info("response={}", response); return response; } @GetMapping("/getProductList") public String getProductList() { List<ProductInfo> productInfoList = productClient.listForOrder(Arrays.asList("164103465734242707")); log.info("response={}", productInfoList); return "ok"; } }
eign用来进行应用之间的通信,在order项目中调用商品服务,应用feign
用的时候需要在pom.xml添加feign依赖。
在启动主类(OrderApplication)上加注解@EnableFeignClients。
在客户端定义好要调用的服务和接口(ProductClient),这里是要调用商品服务的商品详情接口productMsg(),主要是通过@FeignClient匹配服务@GetMapping匹配方法的。
在客户端添加ClientController类,依赖注入ProductClient,调用ProductClient的getProductMsg()。