天天看點

Java版Spring Cloud B2B2C o2o社交電商-搭建Eureka注冊中心

一 建立一個Spring Boot工程,命名為eureka-server,并在pom.xml中引入必要的依賴,代碼如下。

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.7.RELEASE</version>
        <relativePath/>
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
 
        <!--<dependency>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-actuator</artifactId>-->
        <!--</dependency>-->
    </dependencies>
 
    <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>           

二 通過@EnableEurekaServer注解啟動一個服務注冊中心提供給其他應用程式進行對話,隻需要在Spring  Boot應用中添加下面這個注解就能開啟此功能。

@EnableEurekaServer
@SpringBootApplication
public class Application {
 
    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }
 
}           

三 在預設情況下,服務注冊中也會将自己作為用戶端來嘗試注冊它自己,是以需要禁用它的用戶端行為。

application.properties中增加如下配置。

spring.application.name=eureka-server
server.port=1111
 
eureka.instance.hostname=localhost
 
# 關閉保護機制
#eureka.server.enable-self-preservation=false
 
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
 
logging.file=${spring.application.name}.log           

說明:

eureka.client.register-with-eureka:由于該應用為注冊中心,是以設定為false,代表不向注冊中心注冊自己。

eureka.client.fetch-registry:由于注冊中心的職責就是維護服務執行個體,它并不需要去檢索服務,是以也設定為false。