使用Spring Cloud搭建高可用服务注册中心一共需要以下三个步骤:创建一个Eureka Server项目、配置Eureka Server集群、使用Spring Cloud的客户端注册服务。

1. 创建一个Eureka Server项目

首先,需要创建一个Spring Boot项目,引入Eureka Server的依赖。在pom.xml文件中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
</dependencies>

然后,在Spring Boot的启动类上添加@EnableEurekaServer注解,开启Eureka Server功能。

// 导入注解
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 Server项目就创建完成了。

2. 配置Eureka Server集群

为了实现高可用性,我们需要配置一个Eureka Server集群。可以将Eureka Server项目部署在多个节点上,互相注册为对方的服务注册中心。以两个节点为例:

首先,分别创建两个Eureka Server项目,配置同样的依赖和@EnableEurekaServer注解。

然后,在两个项目的配置文件(application.properties或application.yml)中配置互相注册的信息。例如,配置第一个节点注册到第二个节点:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8762/eureka/

配置第二个节点注册到第一个节点:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

这样,两个Eureka Server节点就相互注册为对方的服务注册中心了。

3. 使用Spring Cloud的客户端注册服务

在服务提供者和服务消费者的Spring Boot项目中,需要引入Eureka Client的依赖。在pom.xml文件中添加以下依赖:

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
</dependencies>

然后,在服务提供者的配置文件中,配置Eureka客户端的信息。例如:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true # 使用IP地址注册服务
    leaseRenewalIntervalInSeconds: 30 # 心跳间隔时间
    leaseExpirationDurationInSeconds: 90 # 实例过期时间

然后,在服务提供者的启动类上添加@EnableDiscoveryClient注解,开启服务注册功能。

// 导入注解
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceProviderApplication.class, args);
    }
}

在服务消费者的配置文件中,也配置Eureka客户端的信息。例如:

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

然后,在服务消费者中使用@LoadBalanced注解,开启负载均衡功能。例如:

// 导入注解
import org.springframework.cloud.client.loadbalancer.LoadBalanced;

@SpringBootApplication
@EnableDiscoveryClient
public class ServiceConsumerApplication {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }
}

至此,我们就成功使用Spring Cloud搭建了一个高可用的服务注册中心。