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

相关推荐
骇客野人12 小时前
基于Nginx+Eureka+Apollo+Jenkins+SpringBoot Web系统分布式部署方案
nginx·eureka·jenkins
vx-程序开发12 小时前
springboot旅游推介平台---附源码24175
java·spring boot·python·spring cloud·eclipse·django·idea
wsad05322 天前
CentOS Stream 10 Docker 容器无法访问外网:xt_addrtype 内核模块缺失解决方法
linux·网络·docker·云原生·eureka·centos
bosins3 天前
Ubuntu 24.04部署llama.cpp下载资源一直中断的解决方案
ubuntu·eureka·llama
952363 天前
Spring-cloud配置中心
java·spring·spring cloud·微服务
Ghost Face...3 天前
龙芯Docker全流程:安装到离线迁移实战
java·docker·eureka
ruofu334 天前
如何让docker使用提前下载好的镜像,而不是在线拉取
java·spring cloud·docker
童槿顏丶4 天前
docker自动化部署脚本
docker·eureka·自动化
过客随尘6 天前
网关扩容了,流量却还是打不过去?企业级 Spring Cloud Gateway 生产动态化部署实战
spring cloud·微服务·架构
攻城有术6 天前
专项攻克-springcloud及其组件
后端·spring·spring cloud