SpringCloud——OpenFeign

发布于:2025-06-07 ⋅ 阅读:(21) ⋅ 点赞:(0)

概述:

OpenFeign是基于Spring的声明式调用的HTTP客户端,大大简化了编写Web服务客户端的过程,用于快速构建http请求调用其他服务模块。同时也是spring cloud默认选择的服务通信工具。

使用方法:

 RestTemplate手动构建:

// 带查询参数的Get请求
String url = "https://api.example.com/users?name={name}&age={age}";
Map<String, Object> params = new HashMap<>();
params.put("name", "John");
params.put("age", 25);
User users = restTemplate.getForObject(url, User.class, params);
// 简单Post请求
String url = "https://api.example.com/users";
User newUser = new User("John", "Doe");
User createdUser = restTemplate.postForObject(url, newUser, User.class);

OpenFeign声明式接口:

相较于RestTemplate和OkHttp完整构建请求头、请求体和url的过程。OpenFeign支持声明服务接口类,并使用springMVC的风格定义请求(@RequestMapping)。

@FeignClient(name = " ",url=" ")

我们需要创建一个接口并使用@FeingClient注解声明接口

  • 没有使用nacos,则我们需要在url中指定对应模块的http地址(包含IP和端口)
  • 使用了nacos,则@FeingClient会通过name获取对应实例列表(动态服务发现),并通过负载均衡获取其中一个健康实例的IP和端口等信息(负载均衡)
  • FeignClient最后会在FeignClientFactory中拼接模块实例的IP、端口和当前接口方法的RequestMapping信息生成构建好的http客户端对象(动态代理对象)并注入到spring容器中
// 启用组件
@SpringBootApplication
@EnableDiscoveryClient  // 启用Nacos服务发现(可选,选择后可通过FeignClient注解的name属性获取对应模块实例列表)
@EnableFeignClients     // 启用OpenFeign(为FeignClient生成动态代理对象并注入到spring容器中)
public class Application { }
// 如果未结合服务注册(Nacos)则需要硬编码指定url
@FeignClient(name = "user-service",url = "")
public interface UserClient {
    @GetMapping("/users/{id}")
    User getUser(@PathVariable Long id);
}
// 扫描对应包下的FeignClient接口(一般放在公共依赖中)
@EnableFeignClients(basePackages = "com.example.feign.api")
@SpringBootApplication
public class OrderApplication { ... }

补充:

整合了OpenFeign和Nacos后才能通过name属性发现nacos中注册好的模块实例列表并通过Ribbon或LoadBalancer的负载均衡策略选择适合的健康实例,构建对应的代理对象到spring容器中。

我们可以实现RequestInterceptor接口来对请求进行拦截,实现请求的精细控制。


网站公告

今日签到

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