服务发现与注册:Eureka与Nacos
服务发现与注册:Eureka与Nacos
概述
服务发现是微服务架构的核心组件。本教程介绍Eureka和Nacos的使用。
1. Eureka
// Eureka Server
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
// Eureka Client
import org.springframework.cloud.netflix.eureka.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
// 配置
# application.yml
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
2. Nacos
// Nacos Server
// 启动Nacos服务器
// sh startup.sh -m standalone
// Nacos Client
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class NacosApplication {
public static void main(String[] args) {
SpringApplication.run(NacosApplication.class, args);
}
}
// 配置
# application.yml
spring:
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml
3. 实际应用示例
服务调用
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
@Service
public class ServiceDiscoveryService {
private final DiscoveryClient discoveryClient;
public ServiceDiscoveryService(DiscoveryClient discoveryClient) {
this.discoveryClient = discoveryClient;
}
public ServiceInstance getServiceInstance(String serviceName) {
List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
if (instances.isEmpty()) {
throw new RuntimeException("服务不可用: " + serviceName);
}
return instances.get(0);
}
public String getServiceUrl(String serviceName) {
ServiceInstance instance = getServiceInstance(serviceName);
return instance.getUri().toString();
}
}
配置管理
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
@Component
@RefreshScope
public class DynamicConfig {
@Value("${app.feature.enabled:false}")
private boolean featureEnabled;
@Value("${app.config.value:default}")
private String configValue;
public boolean isFeatureEnabled() {
return featureEnabled;
}
public String getConfigValue() {
return configValue;
}
}
4. 最佳实践
- 选择合适的服务发现工具:Eureka简单,Nacos功能丰富
- 健康检查:确保服务可用性
- 负载均衡:使用Ribbon或LoadBalancer
- 配置管理:使用配置中心统一管理配置
- 监控告警:监控服务状态
总结
服务发现是微服务架构的核心组件。掌握Eureka和Nacos的使用,可以构建可扩展、高可用的微服务系统。