# 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可選 |
健康檢查 | 心跳 | 多種方式 | 多種方式 |
配置中心 | 不支持 | 支持 | 支持 |
雪崩保護 | 有 | 無 | 有 |
社區活躍度 | 維護模式 | 活躍 | 非?;钴S |
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。