一, Feign 实现应用间的通信
声明式 REST 客户端 (伪 RPC), 采用基于接口的注解. 本质上是 Http 客户端, Http 远程调用.
1, 在 Order 工程中的 pom 文件增加
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-openfeign</artifactId>
- </dependency>
2, 增加注解 @EnableFeignClients
3, 声明要调用的接口
- package com.example.demo.client;
- import org.springframework.cloud.openfeign.FeignClient;
- import org.springframework.web.bind.annotation.GetMapping;
- /**
- * 需要在 Product 服务中要调的接口
- */
- @FeignClient(name = "product") //product 代表访问 product 应用下的 msg 接口
- public interface ProductClient {
- @GetMapping("/msg") //
- String productMsg();
- }
4, 在 Order 应用调用
二, Product 工程
1, 增加 List<ProductInfo> findByProductIdIn(List<String> productIdList); 方法
- package com.example.product.repository;
- import com.example.product.dataobject.ProductInfo;
- import org.springframework.data.jpa.repository.JpaRepository;
- import java.util.List;
- public interface ProductInfoRepository extends JpaRepository<ProductInfo, String> {
- // 查询所有在架的商品
- List<ProductInfo> findByProductStatus(Integer productStatus);
- List<ProductInfo> findByProductIdIn(List<String> productIdList);
- }
2,Server 层
- @Service
- public class ProductServiceImpl implements ProductService{
- @Autowired
- private ProductInfoRepository productInfoRepository;
- /**
- * 查询商品列表
- *
- * @param productIdList
- */
- @Override
- public List<ProductInfo> findList(List<String> productIdList) {
- return productInfoRepository.findByProductIdIn(productIdList);
- }
- }
接口
- public interface ProductService {
- /**
- * 查询商品列表
- * @param productIdList
- */
- List<ProductInfo> findList(List<String> productIdList);
- }
3,Controller 层
- @RestController
- @RequestMapping("/product")
- public class ProductController {
- @Autowired
- private ProductService productService;
- /**
- * 获取商品列表 (给订单服务用)
- * @param productIdList
- * @return
- */
- @GetMapping("/listForOrder")
- public List<ProductInfo> listForOrder(List<String> productIdList){
- return productService.findList(productIdList);
- }
- }
来源: http://www.bubuko.com/infodetail-2909400.html