springcloud alibaba(四)OpenFeign实现服务调用

文章目录

OpenFeign实现服务调用
1、什么是OpenFeign

OpenFeign(也常称 Spring Cloud OpenFeign)是 Spring Cloud 生态中的一个声明式的 HTTP 客户端,基于 Netflix Feign 封装而来,旨在简化微服务架构中服务间的 HTTP 远程调用开发。它通过注解化的配置方式,让开发者无需手动编写复杂的 HTTP 请求代码(如 RestTemplate 的拼接 URL、设置请求参数等),仅需定义接口并添加注解,就能实现服务间的远程通信。

2、核心特性

OpenFeign(也常称 Spring Cloud OpenFeign)是 Spring Cloud 生态中的一个声明式的 HTTP 客户端,基于 Netflix Feign 封装而来,旨在简化微服务架构中服务间的 HTTP 远程调用开发。它通过注解化的配置方式,让开发者无需手动编写复杂的 HTTP 请求代码(如 RestTemplate 的拼接 URL、设置请求参数等),仅需定义接口并添加注解,就能实现服务间的远程通信。

2.1、声明式编程

OpenFeign 的核心是接口 + 注解的模式:开发者只需定义一个接口,在接口上添加@FeignClient等注解,指定要调用的远程服务名称,OpenFeign 会自动为该接口生成动态代理实现类,底层完成 HTTP 请求的发送与响应的解析。

2.2、集成 Spring MVC 注解

完全兼容 Spring MVC 的常用注解(如@GetMapping、@PostMapping、@RequestParam、@PathVariable等),开发者无需学习新的注解语法,降低了学习成本。

2.3、负载均衡集成

与 Spring Cloud 的负载均衡组件(如 Ribbon、Spring Cloud LoadBalancer)无缝集成,当远程服务有多个实例时,OpenFeign 会自动实现请求的负载分发。

2.4、熔断器支持

可与 Spring Cloud Circuit Breaker(如 Resilience4j、Sentinel)集成,实现服务调用的熔断、降级,避免服务雪崩。

2.5、请求 / 响应编解码

内置了对 JSON、XML 等数据格式的编解码支持,无需手动处理序列化和反序列化。

2.6、可定制化

支持自定义拦截器(RequestInterceptor)、编码器、解码器、日志级别等,满足个性化的 HTTP 调用需求。

3、OpenFeign的使用
3.1、加入的依赖
xml 复制代码
<!--fegin组件-->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
3.2、在主类上添加注解
java 复制代码
/**
 * 订单启动类
 */
@SpringBootApplication
//@EnableDiscoveryClient
@EnableFeignClients //主类上添加Fegin的注解
public class OrderApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
}
3.3、创建被调用方的Service, 并使用Fegin实现微服务调用
java 复制代码
package com.goblin.feign;

import com.goblin.entity.User;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * 调用用户微服务
 */
//声明调用的提供者的name
//path是路径, 也可以把path的值写到映射路径中
@FeignClient(name = "service-user"/*, path = "/user"*/)
public interface UserClient {
    @GetMapping("/user/{uid}")
    User getByUid(@PathVariable Long uid);
}
java 复制代码
package com.goblin.feign;

import com.goblin.entity.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"/*, path = "/product"*/)
public interface ProductClient {

    @GetMapping("/product/{pid}")
    Product findById(@PathVariable Long pid);
}
3.4、调用方(OrderController)方法代码修改
java 复制代码
   @Resource
   private UserClient userClient;

   @Resource
   private ProductClient productClient;
   
   /**
     * 创建订单
     *
     * @param pid
     * @param uid
     * @return
     */
    @GetMapping("/order/{pid}/{uid}/{byNum}")
    public Order createOrder(@PathVariable Long pid,
                             @PathVariable Long uid,
                             @PathVariable Integer byNum) {

        Order order = new Order();
        //需要远程调用用户微服务获取用户信息
        order.setUid(uid);
        User user = userClient.getByUid(uid);
        log.info("查询到的用户信息: {}", JSON.toJSONString(user));
        order.setUsername(user.getUsername());
        //需要远程调用产品微服务获取产品信息
        order.setPid(pid);
        Product product = productClient.findById(pid);
        log.info("查询到的产品信息: {}", JSON.toJSONString(product));
        order.setPname(product.getPname());
        order.setPprice(0D);
        order.setNumber(byNum);
        orderService.createOrder(order);
        log.info("保存订单成功!");
        return order;
    }
4、重启shop-order服务验证
相关推荐
oak隔壁找我2 小时前
MySQL中 SHOW FULL PROCESSLIST` 输出中 `State` 列的所有可能值
后端
上进小菜猪3 小时前
基于 YOLOv8 的面向文档智能处理的表格区域检测系统 [目标检测完整源码]
后端
oak隔壁找我3 小时前
JVM常用调优参数
java·后端
IT_陈寒7 小时前
React状态管理终极对决:Redux vs Context API谁更胜一筹?
前端·人工智能·后端
晨星shine8 小时前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
蝎子莱莱爱打怪8 小时前
OpenClaw 从零配置指南:接入飞书 + 常用命令 + 原理图解
java·后端·ai编程
倚栏听风雨8 小时前
【ES避坑指南】明明存的是 "CodingAddress",为什么 term 查询死活查不到?彻底搞懂 text 和 keyword
后端
程序员爱钓鱼8 小时前
Go 操作 Windows COM 自动化实战:深入解析 go-ole
后端·go·排序算法
回家路上绕了弯9 小时前
深入解析Agent Subagent架构:原理、协同逻辑与实战落地指南
分布式·后端
子玖9 小时前
实现微信扫码注册登录-基于参数二维码
后端·微信·go