目录
1 概念导入
2 添加依赖
<!-- 远程调用 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3 在启动类上添加注解
@EnableFeignClients
4 编写对应的接口
package com.ax.order.feign;
import com.ax.product.bean.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name = "service-product")
public interface ProductFeignClient {
/**
* 测试FeignClient
*
* @param id
*/
//mvc注解两套使用逻辑
//标注在Controller上,为接收请求
//标注在FeignClient上,为发送请求
@GetMapping("/product/{id}")
Product getProductById(@PathVariable("id") Long id);
//如果调用自己其他服务的api直接将其方法复制过来即可,下面这个就是从product当中复制过来的
@GetMapping("/product/{id}")
Product getProduct(@PathVariable("id") Long id);
}
5 注入并调用
@Autowired
private ProductFeignClient productFeignClient;
@Override
public Order createOrder(Long productId, Long userId) {
// Product product = getProductFromRemote3(productId);
Product product = productFeignClient.getProductById(productId);
Order order = new Order();
order.setId(1L);
// 远程调用计算商品数额
order.setTotalAmount(product.getPrice().multiply(new BigDecimal(product.getNum())));
order.setUserId(userId);
order.setNickName("张三");
order.setAddress("青岛");
// 远程调用获取商品信息
order.setProductList(Arrays.asList(product));
return order;
}
6 日志
配置文件:
logging:
level:
com.ax.order.feign: debug
添加到容器中进行管理:
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
输出样式:
7 超时控制
超时:
相关配置:
spring:
cloud:
openfeign:
client:
config:
default:
logger-level: full
connect-timeout: 1000
read-timeout: 2000
service-product:
logger-level: full
connect-timeout: 3000
read-timeout: 5000