# SpringCloud中Eureka的使用方法 ## 一、Eureka概述 ### 1.1 什么是服务注册与发现 在分布式系统中,服务注册与发现是核心基础设施之一。随着微服务架构的普及,系统被拆分为多个独立服务,服务实例的动态变化(如扩缩容、故障迁移)使得硬编码的服务地址不再适用。 服务注册与发现机制主要解决以下问题: - 服务实例动态注册与注销 - 服务消费者自动感知可用服务列表 - 服务实例健康状态监控 - 客户端负载均衡 ### 1.2 Eureka的基本架构 Eureka采用CS架构,包含两个核心组件: 1. **Eureka Server**:注册中心服务端 - 提供服务注册与发现功能 - 存储所有可用服务节点的信息 - 实现服务健康检查机制 2. **Eureka Client**:注册中心客户端 - 内置在服务提供者和消费者中 - 服务启动时自动注册到Server - 定期发送心跳维持注册 - 从Server获取服务注册信息并缓存  ### 1.3 Eureka的特点 - **AP系统**:优先保证可用性和分区容错性 - **自我保护机制**:网络分区时保护注册信息 - **多级缓存机制**:提高服务发现效率 - **RESTful API**:支持HTTP接口操作 - **Region/Zone设计**:支持跨机房部署 ## 二、环境准备与基础搭建 ### 2.1 开发环境要求 - JDK 1.8+ - Spring Boot 2.3.x+ - Spring Cloud Hoxton.SR12+ - Maven 3.5+ ### 2.2 创建Eureka Server项目 1. 使用Spring Initializr创建项目 ```bash curl https://start.spring.io/starter.zip -d dependencies=cloud-eureka-server -d baseDir=eureka-server -o eureka-server.zip
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
server: port: 8761 eureka: instance: hostname: localhost client: registerWithEureka: false # 不向自己注册 fetchRegistry: false # 不从自己获取注册信息 serviceUrl: defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
启动应用后访问:http://localhost:8761
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
@SpringBootApplication @EnableDiscoveryClient // 或使用@EnableEurekaClient public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } }
spring: application: name: service-provider eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/ instance: instance-id: ${spring.application.name}:${random.value} prefer-ip-address: true lease-renewal-interval-in-seconds: 30 lease-expiration-duration-in-seconds: 90
@RestController public class ConsumerController { @Autowired private DiscoveryClient discoveryClient; @GetMapping("/instances") public List<ServiceInstance> getInstances(@RequestParam String serviceId) { return discoveryClient.getInstances(serviceId); } }
@Bean @LoadBalanced // 启用客户端负载均衡 public RestTemplate restTemplate() { return new RestTemplate(); } @GetMapping("/call") public String callService() { return restTemplate.getForObject( "http://service-provider/api", String.class); }
# 节点1 application-peer1.yml spring: profiles: peer1 eureka: instance: hostname: peer1 client: serviceUrl: defaultZone: http://peer2:8762/eureka/ # 节点2 application-peer2.yml spring: profiles: peer2 eureka: instance: hostname: peer2 client: serviceUrl: defaultZone: http://peer1:8761/eureka/
# 启动第一个节点 java -jar eureka-server.jar --spring.profiles.active=peer1 # 启动第二个节点 java -jar eureka-server.jar --spring.profiles.active=peer2
eureka: server: enable-self-preservation: true # 默认true renewal-percent-threshold: 0.85 # 触发保护的阈值 eviction-interval-timer-in-ms: 60000 # 清理间隔
eureka: instance: metadata-map: cluster: cluster1 version: 1.0 region: us-east
List<ServiceInstance> instances = discoveryClient.getInstances("service-provider"); instances.forEach(instance -> { Map<String, String> metadata = instance.getMetadata(); // 使用metadata信息 });
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .anyRequest().authenticated() .and() .httpBasic(); } }
eureka: client: serviceUrl: defaultZone: http://user:password@localhost:8761/eureka/
检查项:
调试命令:
# 查看注册列表 curl http://localhost:8761/eureka/apps # 检查特定服务 curl http://localhost:8761/eureka/apps/SERVICE-PROVIDER
优化方案: 1. 调整客户端缓存刷新间隔
eureka: client: registry-fetch-interval-seconds: 5 # 默认30秒
@RefreshScope @RestController public class ConsumerController { // ... }
service-provider: ribbon: NIWSServerListClassName: com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList ConnectTimeout: 1000 ReadTimeout: 3000
@FeignClient(name = "service-provider") public interface ProviderClient { @GetMapping("/api") String callApi(); }
eureka: server: response-cache-update-interval-ms: 30000 client: healthcheck: enabled: true registry-fetch-interval-seconds: 30 instance: lease-renewal-interval-in-seconds: 30 lease-expiration-duration-in-seconds: 90
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency>
特性 | Eureka | Consul | Nacos |
---|---|---|---|
一致性协议 | AP | CP | AP/CP可选 |
健康检查 | 心跳 | 多种方式 | 多种方式 |
配置中心 | 不支持 | 支持 | 支持 |
雪崩保护 | 有 | 无 | 有 |
社区活跃度 | 维护模式 | 活跃 | 非常活跃 |
Spring Cloud Netflix进入维护模式后的替代方案:
兼容性矩阵:
Spring Cloud Version | Spring Boot Version |
---|---|
Hoxton | 2.2.x, 2.3.x |
2020.0.x | 2.4.x, 2.5.x |
Eureka作为Spring Cloud体系中的核心组件,提供了简单易用的服务注册与发现能力。本文详细介绍了从环境搭建到生产实践的完整流程,包括:
尽管目前有更多新兴的服务发现方案,Eureka仍然是许多现有系统的稳定选择。理解其核心原理和配置方法,对于构建可靠的微服务架构具有重要意义。
REST API端点:
Actuator端点:
”`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。