一、Feign实现应用间的通信 声明式REST客户端(伪RPC),采用基于接口的注解。本质上是Http客户端,Http远程调用。 1、 在Order工程中的pom文件增加 dependencygroupIdorg.springframework.cloud/group
一、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);
}
}
