天天看點

spring cloud 服務注冊中心

建立“服務注冊中心”

spring cloud的學習都是建立在spring boot基礎上的,是以對spring boot不了解的童鞋先要了解下spring boot項目的搭建以及運作機制。

1.建立springBoot項目

spring cloud 服務注冊中心

2.并在pom.xml中引入需要的依賴

<dependencies>
    <!--eureka 服務依賴,将來其他服務注冊就是注冊到這個項目下,類似于dubbo使用zookeeper作為注冊中心-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
    </dependency>
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
   </dependency>
</dependencies>
<!--用來管理spring cloud,在 <dependency>标簽中引用spring cloud的元件就不需要指定版本資訊 -->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Brixton.SR5</version><!-- 最好使用一些新的版本 -->
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
           

3.在application.properties中添加配置

server.port=
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka/
           

eureka端口,和其他項目區分,保持獨立

server.port=8761

配置主機名

eureka.instance.hostname=eureka-server-01

配置服務注冊中心是否以自己為用戶端進行注冊(配置false)

eureka.client.registerWithEureka=fasle

是否取得注冊資訊(配置false)

eureka.client.fetchRegistry=false

配置eureka用戶端的預設域(該配置可能沒有提示,請複制或者手動輸入,切勿使用有提示的service-url會引起内置tomcat報錯)

eureka.client.serviceUrl.defaultZone=http://localhost:${server.port}/eureka

4.在入口檔案中開啟服務注冊中心

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudServerApplication.class, args);
    }
}
           

5.啟動項目

通路:http://localhost:8761/

spring cloud 服務注冊中心

這樣注冊中心就好了,下面就可以将服務注冊到注冊中心,供消費者調用,大家也許會想一個事,如果注冊中心當機了那不是就慘了嗎?所有調用将死去,是的,是以搭建高可用的注冊中心是非常重要的。

一般來說,搭建高可用的注冊中心架構人員會做,無需普通開發人員關心,其實在spring cloud環境下工作很多事情變得比較容易,下一篇博文我們來搭建高可用的注冊中心。

想了解更多java相關技術,請關注公衆号“JavaEE那些事”

掃描下面二維碼,更多技術資料等你來拿

spring cloud 服務注冊中心

繼續閱讀