# 服务提供者和消费者
概念:
* 服务提供者:服务的被调用方,即:为其他服务提供服务的服务
* 服务消费者:服务的调用方,即:依赖其他服务的服务
服务发现组件:Eureka
Spring Cloud 已经把 Eureka 与 Spring Boot 进行了集成,使用起来更为简单。
这里是提供的一个示例:
* 启动 Eureka Server
Eureka Server 非常简单,只需要三个步骤:
在 pom.xml 中添加依赖:
~~~
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
~~~
实现 Application,添加 annotation。 @EnableEurekaServer、@EnableDiscoveryClient 执行 main 方法启动 Eureka Server。
~~~
@SpringBootApplication
@EnableEurekaServer
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
~~~
运行 Application 即可启动 Server,启动 Server 后打开
* 注册服务
把一个服务注册在 server 中需要以下几个步骤:
添加 eureka 依赖
org.springframework.cloudspring-cloud-starter-eureka
添加 @EnableEurekaClient 注解
~~~
@EnableEurekaClient
public class Application
~~~
3. 在 application.yml 或者 application.properties 中添加配置
~~~
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8761/eureka/
spring:
application:
name: eureka
~~~
配置中有两项需要额外注意:
1. eureka.client.serviceUrl.defaultZone:指定 Eureka 服务端的地址,当客户端没有专门进行配置时,就会使用这个默认地址。
2. [spring.application.name](http://spring.application.name/):服务注册所使用的名称,同时其他服务查找该服务时也使用该名称。我们启动该服务后,可以在管理页面中查看到该服务已经在注册中心中注册成功了