SpringCloud入门Day01-服务注册与发现、服务通信、负载均衡与算法
在Spring Cloud中,服务注册与发现通常使用Eureka来实现。以下是一个简单的例子:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Eureka Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
- 配置Eureka Server:
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
在application.properties
中配置Eureka Server:
spring.application.name=eureka-server
server.port=8761
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
启动Eureka Server后,可以用来注册服务。
服务提供者(Eureka Client):
- 在
pom.xml
中添加Eureka Client依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
- 在
application.properties
中配置服务名称和Eureka Server的地址:
spring.application.name=service-provider
server.port=8080
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
- 启动类添加
@EnableDiscoveryClient
注解:
@EnableDiscoveryClient
@SpringBootApplication
public class ServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceProviderApplication.class, args);
}
}
启动服务提供者后,它会自动注册到Eureka Server。
服务消费者(Eureka Client)通过Ribbon进行负载均衡调用:
- 添加Ribbon依赖到
pom.xml
:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
- 配置服务名称和Eureka Server地址:
spring.application.name=service-consumer
server.port=8081
eureka.client.service-url.defaultZone=http://localhost:8761/eureka/
- 使
评论已关闭