Spring Cloud Alibaba快速入门03-OpenFeign

发布于:2025-09-11 ⋅ 阅读:(19) ⋅ 点赞:(0)


在这里插入图片描述

前言

官网:https://docs.spring.io/spring-cloud-openfeign/reference/spring-cloud-openfeign.html#spring-cloud-feign
注意:OpenFeign 是一个声明式远程调用客户端;
在这里插入图片描述

Feign‌与OpenFeign的异同

‌Feign‌:由Netflix开发,是一个声明式HTTP客户端,通过接口和注解简化远程服务调用,内置Ribbon实现负载均衡,但原生不支持Spring MVC注解。‌‌
‌OpenFeign‌:Spring Cloud团队在Feign基础上二次开发,完全兼容Feign API,新增对Spring MVC注解(如@RequestMapping)的支持,并深度集成Spring Cloud生态(如Eureka、Hystrix)。‌‌

代码示例

远程调用注册中心其他服务

1.services加入依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.启动类中开启功能

@EnableFeignClients //开启Feign远程调用功能
@SpringBootApplication
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
 }   

3.order服务远程调用接口

import com.qf.entity.Product;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

//填写需要远程调用的服务
@FeignClient(value = "qf-service-product") // feign客户端
public interface ProductFeignClient {
    //mvc注解的两套使用逻辑
    //1、标注在Controller上,是接受这样的请求
    //2、标注在FeignClient上,是发送这样的请求
    @GetMapping("/product/{id}")
    Product getProductById(@PathVariable("id") Long id);
}

4.order服务使用

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public Order createOrder(Long userId, Long productId) {
//        Product product = getProductFromRemoteWithLoadBalanceAnnotation(productId);
        Product product = productFeignClient.getProductById(productId);
        Order order = new Order();
        order.setId(1L);
        order.setUserId(userId);
        order.setTotalAmount(new BigDecimal(100));
        order.setAddress("北京");
        order.setProductList(Arrays.asList(product));
        return order;
    }

注意:调用商品服务时会自动负载均衡
在openfeign中写的远程调用接口和在controller写接口的格式相同。

远程调用第三方接口代码示例

可以通过openFeign直接调用第三方接口

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PostMapping;

/**
 * 调用第三方接口api
 */
@FeignClient(value = "test-client", url = "https://blog.csdn.net/weixin_46425661")
public interface TestFeignClient {


    @PostMapping("/article/details/151195266")
    String getDetails();
}

测试类

@SpringBootTest
public class LoadBalancerTest {

    @Autowired
    private TestFeignClient testFeignClient;

    @Test
    void Test(){
        String details = testFeignClient.getDetails();
        System.out.println("details = " + details);
    }
}

总结

如果指定了url地址,所以会向该指定url发送请求。
如果没有指定url地址则,则openfeign自动连上注册中心,寻找对应的服务名对应的可访问列表
如何编写好OpenFeign声明式的远程调用接口?
• 业务API:直接复制对方Controller签名即可
• 第三方API:根据接口文档确定请求如何发

面试题:客户端负载均衡与服务端负载均衡区别

在这里插入图片描述
当发起调用的一端自己发起负载均衡算法,选择一个被调用的服务,则为客户端负载均衡。如openfeign
如调用第三方的接口时,由第三方的服务端进行负载均衡算法,则为服务端负载均衡



网站公告

今日签到

点亮在社区的每一天
去签到