Eureka學習例子


Eureka學習

例子學習地址:https://github.com/MyCreazy/EurekaStudy

這里有參考http://blog.csdn.net/nero__a/article/details/65631367進行總結操作

Spring Cloud下有很多工程:

  • Spring Cloud Config:依靠git倉庫實現的中心化配置管理。配置資源可以映射到Spring的不同開發環境中,但是也可以使用在非Spring應用中。
  • Spring Cloud Netflix:不同的Netflix OSS組件的集合:Eureka、Hystrix、Zuul、Archaius等。
  • Spring Cloud Bus:事件總線,利用分布式消息將多個服務連接起來。非常適合在集群中傳播狀態的改變事件(例如:配置變更事件)
  • Spring Cloud Consul:服務發現和配置管理,由Hashicorp團隊開發。我決定先從Spring Cloud Netflix看起,它提供了如下的功能特性:
  • 服務發現:Eureka-server實例作為服務提供者,可以注冊到服務注冊中心,Eureka客戶端可以通過Spring管理的bean發現實例;
  • 服務發現:嵌套式的Eureka服務可以通過聲明式的Java配置文件創建;
  • 斷路器:利用注解,可以創建一個簡單的Hystrix客戶端;
  • 斷路器:通過Java配置文件可以創建內嵌的Hystrix控制面板;
  • 聲明式REST客戶端:使用Feign可以創建聲明式、模板化的HTTP客戶端;
  • 客戶端負載均衡器:Ribbon
  • 路由器和過濾器:Zuul可以在微服務架構中提供路由功能、身份驗證、服務遷移、金絲雀發布等功能。

1. 服務注冊中心

在IDEA中創建一個Spring Cloud工程,引入Eureka-Server包,pom文件整體如下:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>com.sl</groupId>

  <artifactId>RegistryCenter</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

 

  <name>RegistryCenter</name>

  <url>http://maven.apache.org</url>

 

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

 

 <parent>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-parent</artifactId>

    <version>1.3.5.RELEASE</version>

    <relativePath/>

</parent>

<dependencies>

<!-- 用於注冊中心訪問賬號認證 -->

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-security</artifactId>

</dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-test</artifactId>

   <scope>test</scope>

    </dependency>

    <!-- 注冊中心所需的包 -->

    <dependency>

        <groupId>org.springframework.cloud</groupId>

   <artifactId>spring-cloud-starter-eureka-server</artifactId>

    </dependency>

</dependencies>

<dependencyManagement>

    <dependencies>

        <dependency>

       <groupId>org.springframework.cloud</groupId>

       <artifactId>spring-cloud-dependencies</artifactId>

       <version>Brixton.RELEASE</version>

       <type>pom</type>

       <scope>import</scope>

   </dependency>

    </dependencies>

</dependencyManagement>

<!-- spring boot的maven打包插件 -->

    <build>

    <defaultGoal>compile</defaultGoal>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

</project>

 

創建APP類,並用@EnableEurekaServer和@SpringBootApplication兩個注解修飾,后者是Spring Boot應用都需要用的,這里不作過多解釋;@EnableEurekaServer注解的作用是觸發Spring Boot的自動配置機制,由於我們之前在pom文件中導入了eureka-server,spring boot會在容器中創建對應的bean。Eureka的代碼如下:

package com.sl.RegistryCenter;

 

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

 

/**

 * Hello world!

 *

 */

@EnableEurekaServer

@SpringBootApplication

public class App {

        public static void main(String[] args) {

               new SpringApplicationBuilder(App.class).web(true).run(args);

        }

}

添加配置文件application.properties,並且添加如下參數,才能創建一個真正可以使用的服務注冊中心。

######eureka服務端######

spring.application.name=eureka-server

 #驅逐下線的服務,間隔,5秒,默認是60,建議開發和測試環境配置

 eureka.server.evictionIntervalTimerInMs=10000

server.port=8761

#是否需要注冊到注冊中心,因為該項目本身作為服務注冊中心,所以為false

 eureka.client.register-with-eureka=false

 #是否需要從注冊中心獲取服務列表,原因同上,為false

 eureka.client.fetch-registry=false

 security.basic.enabled=true

security.user.name=admin

security.user.password=123

#注冊服務器的地址:服務提供者和服務消費者都要依賴這個地址

 eureka.client.serviceUrl.defaultZone=http://admin:123@localhost:8761/eureka

 ###Eureka自我保護機制,為true表示開,false表示關,默認為開####

 eureka.server.enable-self-preservation=true

 

啟動注冊服務,並訪問:http://localhost:8761,就可以看到如下界面。

 

 

2. 服務提供者

        創建一個Spring Boot工程,代表服務提供者,該服務提供者會暴露一個當前請求產生的時間字符串。

 

工程的pom文件內容如下:

 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>

 

   <groupId>com.sl</groupId>

   <artifactId>TestMicroService</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>jar</packaging>

 

   <name>TestMicroService</name>

   <url>http://maven.apache.org</url>

 

   <properties>

      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

   </properties>

 

   <parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.3.5.RELEASE</version>

      <relativePath /> <!-- lookup parent from repository -->

   </parent>

   <dependencies>

      <dependency>

         <groupId>org.springframework.boot</groupId>

         <artifactId>spring-boot-starter-test</artifactId>

         <scope>test</scope>

      </dependency>

      <dependency>

         <groupId>org.springframework.cloud</groupId>

         <artifactId>spring-cloud-starter-eureka</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.RELEASE</version>

            <type>pom</type>

            <scope>import</scope>

         </dependency>

      </dependencies>

   </dependencyManagement>

    <build>

    <defaultGoal>compile</defaultGoal>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

</project>

其中的關鍵在於spring-cloud-starter-eureka這個Jar包,其中包含了eureka的客戶端實現。

在src/main/java/com.sl.TestMicroService下創建工程的主類App,使用@EnableDiscoveryClient注解修飾,該注解在服務啟動的時候,可以觸發服務注冊的過程,向配置文件中指定的服務注冊中心(Eureka-Server)的地址注冊自己提供的服務。App的源碼如下:

 

package com.sl.TestMicroService;

 

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.boot.builder.SpringApplicationBuilder;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

 

/**

 * Hello world!

 *

 */

@EnableDiscoveryClient

@SpringBootApplication

public class App {

 

   public static void main(String[] args) {

      new SpringApplicationBuilder(App.class).web(true).run(args);

   }

}

application.properties配置文件的內容如下:

server.port=8111

#設置應用的名稱

spring.application.name=microservice-provider-user

#服務注冊的Eureka Server地址

eureka.client.serviceUrl.defaultZone=http://admin:123@localhost:8761/eureka

#設置注冊ip

eureka.instance.prefer-ip-address=true

#自定義應用實例id

#健康檢查

eureka.client.healthcheck.enabled=true

服務提供者的基本框架搭好后,需要實現服務的具體內容,在ComputeController類中實現,它的具體代碼如下:

package com.sl.TestMicroService;

 

import java.text.SimpleDateFormat;

import java.util.Date;

 

import org.apache.log4j.Logger;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cloud.client.ServiceInstance;

import org.springframework.cloud.client.discovery.DiscoveryClient;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class ComputeController {

        private final Logger logger = Logger.getLogger(getClass());

        @Autowired

        private DiscoveryClient client;

 

        private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

 

        @RequestMapping(value = "/test", method = RequestMethod.GET)

        public String test() {

               ServiceInstance instance = client.getLocalServiceInstance();

               String temp = "當前時間【" + df.format(new Date()) + "】/add, host:" + instance.getHost() + ", service_id:"

                               + instance.getServiceId();

               logger.info(temp);

               return temp;

        }

}

先啟動服務注冊中心的工程,然后再啟動服務提供者,在訪問:localhost:8761,如下圖所示,服務提供者已經注冊到服務注冊中心啦,下圖可以查看

 

在Spring Cloud Netflix中,使用Ribbon實現客戶端負載均衡,使用Feign實現聲明式HTTP客戶端調用——即寫得像本地函數調用一樣。

3. 服務消費者-Feign

pom配置如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>

 

  <groupId>com.sl</groupId>

  <artifactId>ServiceConsumer</artifactId>

  <version>0.0.1-SNAPSHOT</version>

  <packaging>jar</packaging>

 

  <name>ServiceConsumer</name>

  <url>http://maven.apache.org</url>

<parent>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-parent</artifactId>

      <version>1.3.5.RELEASE</version>

      <relativePath /> <!-- lookup parent from repository -->

   </parent>

  <properties>

    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

  </properties>

 

  <build>

    <defaultGoal>compile</defaultGoal>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

 

   <dependencies>

        <!-- Feign實現聲明式HTTP客戶端 -->

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-feign</artifactId>

        </dependency>

 

        <!-- eureka客戶端 -->

        <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-starter-eureka</artifactId>

        </dependency>

 

        <!-- spring boot實現Java Web服務-->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-web</artifactId>

        </dependency>

 

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-test</artifactId>

            <scope>test</scope>

        </dependency>

    </dependencies>

   

    <dependencyManagement>

      <dependencies>

         <dependency>

            <groupId>org.springframework.cloud</groupId>

            <artifactId>spring-cloud-dependencies</artifactId>

            <version>Brixton.RELEASE</version>

            <type>pom</type>

            <scope>import</scope>

         </dependency>

      </dependencies>

   </dependencyManagement>

</project>

 

首先創建應用程序啟動類:ConsumerApp,代碼如下:

package com.sl.ServiceConsumer;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

import org.springframework.cloud.netflix.feign.EnableFeignClients;

 

/**

 * Hello world!

 *

 */

@EnableDiscoveryClient // 用於啟動服務發現功能

@EnableFeignClients // 用於啟動Fegin功能

@SpringBootApplication

public class ConsumerApp {

 

        /**

         * main函數入口

         *

         * @param args

         */

        public static void main(String[] args) {

               SpringApplication.run(ConsumerApp.class);

        }

}

然后創建ComputeClient接口,使用@FeignClient("microservice-provider-user")注解修飾,microservice-provider-user就是服務提供者的名稱,然后定義要使用的服務,代碼如下:

package com.sl.ServiceConsumer;

 

import org.springframework.cloud.netflix.feign.FeignClient;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

 

@FeignClient("microservice-provider-user")

public interface ConsumerClient {

        // @RequestMapping(method = RequestMethod.GET, value = "/add")

        // Integer add(@RequestParam(value = "a") Integer a, @RequestParam(value =

        // "b") Integer b);

 

        @RequestMapping(method = RequestMethod.GET, value = "/test")

        String test();

}

在ConsumerController中,像引入普通的spring bean一樣引入ComputeClient對象,其他的和Ribbon的類似。

 

package com.sl.ServiceConsumer;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;

 

@RestController

public class ConsumerController {

        @Autowired

        private ConsumerClient computeClient;

 

        @RequestMapping(value = "/test", method = RequestMethod.GET)

        public String test() {

               return computeClient.test();

        }

}

application.properties的內容如下:

#應用名稱

spring.application.name=fegin-consumer

#端口號

server.port=9000

 

#注冊中心的地址

eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/

 

啟動fegin消費者,訪問localhost:9000/add,也可以看到服務提供者已經收到了消費者發來的請求。

可以看到兩個服務輪流被調用

 注意事項

1.關於版本對應問題

  • Angel版本對應Spring Boot 1.2.x
  • Brixton版本對應Spring Boot 1.3.x
  • Camden版本對應Spring Boot 1.4.x

2.直接打包

打包時記得引用下面的包

  <build>

    <defaultGoal>compile</defaultGoal>

        <plugins>

            <plugin>

                <groupId>org.springframework.boot</groupId>

                <artifactId>spring-boot-maven-plugin</artifactId>

            </plugin>

        </plugins>

    </build>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM