该栏目讲叙微服务概念、注册中心、负载均衡、配置中心、服务熔断、服务消费等知识


文章目录


简介

  • 简介:Feign 是一个轻量级的 HTTP 客户端,也是实现了 负载均衡 和 REST 调用的开源框架
  • 目的:简化 RestTemplate 代码,实现了 Ribbon 负载均衡,使代码更加简洁
  • 使用步骤
    • 消费者服务添加 Feign 依赖
    • 在业务层接口中添加 @FeignClient 注解,声明需要调用的服务
    • 在业务层接口的抽象方法中使用请求注解配置服务
    • 在启动类添加 @EnableFeignClients 注解激活 Feign

案例

  • 相关依赖
// 注入相关依赖
<dependencies>
    <!--eureka客户端-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <!--feign依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!--web依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--Pom依赖-->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
</dependencies>
  • 编写被调用服务的业务层接口
/**
 * 订单服务使用Feign组件调用产品服务
 */
@FeignClient("product-service")
public interface ProductService {

    @GetMapping("/product/getAllProducts")
    List<Product> getAllProducts();

}
  • 调用服务
/**
 * 使用Fegin调用微服务
 */
@Service
public class OrderServiceFeignImpl implements OrderService {

    @Autowired
    private ProductService productService;

    @Override
    public Order findOrderById(int orderId) {
        return new Order(orderId, "order001", 10000,
                productService.getAllProducts());
    }

}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐