Eureka 与 Feign(一)

Eureka 与 Feign 知识解析

1. Eureka

Spring Cloud Eureka 是服务发现组件,包含:

  • Eureka Server:注册中心,管理服务实例
  • Eureka Client:服务实例,向注册中心注册/获取服务信息

核心功能:

  • 服务注册与发现
  • 心跳检测(默认30秒)
  • 服务故障自动剔除
  • 客户端缓存注册信息
2. OpenFeign

声明式 HTTP 客户端工具,核心特性:

  • 基于接口的声明式调用
  • 整合 Ribbon 实现负载均衡
  • 整合 Hystrix 实现熔断(需额外配置)
  • 自动处理 HTTP 请求/响应序列化
依赖关系
xml 复制代码
<!-- Eureka Server -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

<!-- Eureka Client + OpenFeign -->
<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>

完整示例代码

1. Eureka Server (服务注册中心)

application.yml

yaml 复制代码
server:
  port: 8761
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

EurekaServerApplication.java

java 复制代码
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
}
2. Service Provider (服务提供者)

application.yml

yaml 复制代码
server:
  port: 8081
spring:
  application:
    name: user-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

UserController.java

java 复制代码
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "用户" + id, "user" + id + "@example.com");
    }
}

// 实体类
public class User {
    private Long id;
    private String name;
    private String email;
    // 构造方法/getters/setters
}
3. Service Consumer (服务消费者)

application.yml

yaml 复制代码
server:
  port: 8080
spring:
  application:
    name: order-service
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

Feign Client 接口

java 复制代码
@FeignClient(name = "user-service")
public interface UserServiceClient {
    @GetMapping("/users/{id}")
    User getUserById(@PathVariable("id") Long userId);
    
    // 请求参数示例
    @GetMapping("/users/search")
    User searchUser(@RequestParam("name") String name);
}

OrderController.java

java 复制代码
@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private UserServiceClient userServiceClient;

    @GetMapping("/{orderId}/user")
    public User getOrderUser(@PathVariable Long orderId) {
        // 通过Feign调用用户服务
        Long userId = orderId * 10; // 模拟用户ID
        return userServiceClient.getUserById(userId);
    }
}

启用Feign (主类)

java 复制代码
@SpringBootApplication
@EnableFeignClients
public class OrderServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }
}
4. 高级配置

自定义Feign配置

java 复制代码
@Configuration
public class FeignConfig {
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL; // 详细日志
    }
    
    @Bean
    public RequestInterceptor authInterceptor() {
        return template -> template.header("Authorization", "Bearer token123");
    }
}

使用配置

java 复制代码
@FeignClient(
    name = "user-service",
    configuration = FeignConfig.class,
    fallback = UserServiceFallback.class // 熔断回退
)
public interface UserServiceClient { ... }

熔断回退实现

java 复制代码
@Component
public class UserServiceFallback implements UserServiceClient {
    @Override
    public User getUserById(Long userId) {
        return new User(0L, "备用用户", "fallback@example.com");
    }
}

日志配置 (application.yml)

yaml 复制代码
logging:
  level:
    org.springframework.cloud.openfeign: DEBUG

测试流程

  1. 启动 Eureka Server (8761端口)
  2. 启动 User Service (8081端口)
  3. 启动 Order Service (8080端口)
  4. 访问测试:http://localhost:8080/orders/123/user

关键概念总结

  1. 服务注册:Provider 启动时向 Eureka 注册信息
  2. 服务发现:Consumer 通过服务名发现 Provider
  3. 负载均衡:Feign 自动实现多实例轮询
  4. 声明式调用:定义接口即完成远程调用
  5. 熔断机制:快速失败 + 服务降级

:当前 Spring Cloud 版本默认使用 LoadBalancer 替代 Ribbon,最新版 OpenFeign 已内置负载均衡能力。

通过这个完整示例,可以清晰看到Eureka实现服务治理、Feign简化服务调用的协作过程,是构建微服务架构的基础设施。

相关推荐
sniper_fandc几秒前
Spring Cloud系列—简介
spring cloud
黑暗也有阳光41 分钟前
@FeignClient 中 fallbackFactory 与 fallback 的区别详解
spring boot·spring·spring cloud
黑暗也有阳光44 分钟前
Sentinel 与 Hystrix 熔断降级机制对比解析
分布式·spring cloud·微服务
JavaArchJourney4 小时前
Spring Cloud Hystrix 核心原理
后端·spring cloud
求知若渴,虚心若愚。5 小时前
docker相关操作记录
docker·容器·eureka
白云coy15 小时前
如何在 Ubuntu 24.04 LTS 上安装 Docker
ubuntu·docker·eureka
林林code20 小时前
从源码的角度解读 Nacos 是如何动态刷新配置的
spring cloud
太阳之神aboluo21 小时前
SpringCloud (4) 分布式事务
java·spring·spring cloud
林林code1 天前
Springboot中的yml为单个的服务配置Feign不生效.md
spring cloud