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简化服务调用的协作过程,是构建微服务架构的基础设施。

相关推荐
0w0不秃头程序猿1 天前
guide哥AI智能面试项目部署过程
云原生·eureka
linux修理工1 天前
EasyVoice 项目部署与使用指南(开源文字互转声音)
云原生·eureka
邓草1 天前
Ubuntu修改docker数据目录的方法
ubuntu·docker·eureka
Anthony_CH1 天前
window系统无虚拟化安装Docker的方式
docker·容器·eureka
WZTTMoon1 天前
Spring Boot 启动报错:OpenFeign 隐性循环依赖,排查了整整一下午
java·spring boot·后端·spring cloud·feign
冬天豆腐2 天前
Springcloud,Nacos管理,打jar包后,启动报错
java·spring cloud·maven·jar
爱吃山竹的大肚肚2 天前
依赖冲突快速解决
java·spring boot·后端·spring cloud·maven
用户8307196840822 天前
Spring Boot 启动报错:OpenFeign 隐性循环依赖,排查了整整一下午
java·spring boot·spring cloud
indexsunny2 天前
互联网大厂Java面试实战:从Spring Boot到微服务架构的音视频场景解析
java·spring boot·spring cloud·mybatis·spring security·jwt·flyway
小王不爱笑1322 天前
从 Servlet 生命周期到 Tomcat 执行原理:Web 服务的底层逻辑全解析
eureka