ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

微服务架构远程调用——Feign

2026/8/15 23:22:57 拓冰建站 浏览量
微服务架构远程调用——Feign

文章目录

    • Feign基本使用
      • 添加依赖
      • 创建Feign接口,添加@FeignClient注解
      • controller调用
      • 启动类增加@EnableFeignClients注解
      • 启动服务

Feign是Netflix开发的声明式、模块式的 HTTP 客户端,用于简化对 RESTful API 的调用。它的主要使用场景是在微服务架构中,通过 HTTP 协议调用其他服务的 RESTful API。Feign 支持多种编解码器,如 Jackson、Gson、JAXB 等,可以将请求和响应转换成对象。Feign 还整合了Ribbon和Eureka等服务注册中心来自动发现和负载均衡服务。

Feign基本使用

添加依赖

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>

创建Feign接口,添加@FeignClient注解

@FeignClient(name = "microservice-provider-user") // 客户端名称
public interface UserFeignClient {@RequestMapping(value = "/{id}", method = RequestMethod.GET)public User findById(@PathVariable("id") Long id);
}

controller调用

@RestController
public class MovieController {@Autowiredprivate UserFeignClient userFeignClient;@GetMapping("/user/{id}")public User findById(@PathVariable Long id){return userFeignClient.findById(id);}
}

启动类增加@EnableFeignClients注解

@EnableDiscoveryClient
@SpringBootApplication
@EnableFeignClients
public class ConsumerApplication {public static void main(String[] args) {SpringApplication.run(ConsumerApplication.class, args);}
}

启动服务

eureka ——> provider注册——>consumer调用

可发现feign不但实现了声明式的REST API调用,还实现了客户端测的负载均衡