1. 程式人生 > 其它 >SpringCloud註冊中心

SpringCloud註冊中心

1. 引言

總體微服務流程類似:

SpringCloud是基於SpringBoot的,所以會存在版本的相容性問題,

2. 遠端呼叫

因為不同的服務部署在不同的機器上,所以我們需要使用遠端呼叫的方式去獲取資料(把RestTemplate註冊進IOC容器中)

@Bean
public RestTemplate restTemplate(){
    return new RestTemplate();
}
-------------------------------------
// 設定url
String url = "http://localhost:8081/user/" + order.getUserId();
// 傳送get請求
ResponseEntity<User> forEntity = restTemplate.getForEntity(url, User.class);
// 獲取物件
User body = forEntity.getBody();
++++++++++++++++++++++++++++++++++++
//需要引數的請求
// 設定url,使用{}佔位
String url = "http://localhost:8081/user?id={id}&name={name}";
// 傳送get請求,最後傳入id和name
ResponseEntity<User> forEntity = restTemplate.getForEntity(url, User.class,1,"xx");
// 獲取物件
User body = forEntity.getBody();

2. 註冊中心

對於多個微服務,我們要知道每個微服務的地址(ip+port),使用註冊中心可以幫助我們記錄下每個服務的地址(叢集也可以,幫助我們從叢集中按照規則獲取一個可用的地址)。程式碼中只需要知道微服務的名字就可以通過註冊中心獲取ip+port
註冊中心一般分為兩種(都是基於robbin):Eureka 和 Nacos

2.1 Eureka

2.1.1 建立一個新的maven空模組

2.1.2 匯入Eureka的starts(別忘了匯入SpringCloud相關依賴)

<!-- springCloud -->
<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-dependencies</artifactId>
     <version>${spring-cloud.version}</version>
     <type>pom</type>
     <scope>import</scope>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

2.1.3 編寫啟動類【在@SpringBootApplication 註解標註的主類上加上 @EnableEurekaServer 註解】

2.1.4 編寫yml配置檔案

server:
  port: 10086
spring:
  application:
    name: eureka-server
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

2.1.5 給所有需要使用註冊中心的模組新增依賴

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

2.1.6 給所有需要使用註冊中心的模組新增yml配置資訊【設定名字和eureka的伺服器地址】

spring:
  application:
    name: %自定義的name%
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:10086/eureka

2.1.7 給RestTemplate的@Bean方法上加上@LoadBalanced註解

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

2.2