1. 程式人生 > 程式設計 >Springcloud Eureka配置及叢集程式碼例項

Springcloud Eureka配置及叢集程式碼例項

springcloud微服務包含的技術種類眾多,eureka作為其註冊中心,一直處於主流,但在今年已經處於永久停更狀態,但其優秀的能力還是值得學習。

整體價格採用聚合工程,後續也存在於聚合工程內。

1.首先配置pom工程的依賴

<dependencies>
    <!-- eureka-server -->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
    </dependency>
    <!-- 引用自己定義的api通用包 -->
   <dependency>
      <groupId>com.bai</groupId>
      <artifactId>cloud-api-common</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--監控-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!-- 一般通用配置 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

2.yml檔案配置格式

注意為了配合後續的叢集,將本地127.0.0.1對映為eureka7001.com等等,具體改host方法自行搜尋。

# 埠
server:
 port: 7001

spring:
 application:
  name: cloud-eureka-server
# Eureka配置
eureka:
 instance:
  # eureka服務端的例項名稱
  hostname: eureka7001.com
 client:
  # false表示不向註冊中心註冊自己
  register-with-eureka: false
  # false表示自己端就是註冊中心,職責就是維護服務例項,並不需要去檢查服務
  fetch-registry: false
  # 設定與Eureka Server互動的地址查詢服務和註冊服務都需要依賴這個地址
  service-url:
   defaultZone: http://localhost:7001/eureka

3.主啟動類

@EnableEurekaServer
@SpringBootApplication
public class Eureka7001 {
  public static void main(String[] args) {
    SpringApplication.run(Eureka7001.class,args);
  }
}

4.配置多個叢集分散式

eureka叢集要遵循互相守望的原則。在自己的yml檔案中去註冊其他所有叢集的地址。除了yml檔案格式,其他大致都相同。

service-url:
defaultZone: http://eureka7002.com:7002/eureka

有多少個叢集就需要在defaultZone中註冊多少個。

注意yml檔案內的程式碼格式要正確,級別要對齊。

本篇所有程式碼均在GitHub:

https://github.com/MaTsukun/springcloud2020

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。