# 服務提供者和消費者
概念:
* 服務提供者:服務的被調用方,即:為其他服務提供服務的服務
* 服務消費者:服務的調用方,即:依賴其他服務的服務
服務發現組件: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/):服務注冊所使用的名稱,同時其他服務查找該服務時也使用該名稱。我們啟動該服務后,可以在管理頁面中查看到該服務已經在注冊中心中注冊成功了