SpringCloud---(4)Eureka服务发现组件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq1021979964/article/details/83859416

 

Eureka简介

Eureka是Netflix开发的服务发现框架,本身是一个基于REST的服务,主要用于定位运行在AWS域中的中间层服务,以达到负载均衡和中间层服务故障转移的目的。SpringCloud将它集成在其子项目spring-cloud-netflix中,以实现Spring Cloud的服务发现功能。

Eureka与Spring Boot构建的微服务很容易整合起来。

Eureka包含了服务端和客户端组件。

1.  服务端组件也被称为服务注册中心,用于提供服务的注册与发现。Eureka支持高可用的配置,当集群有分片出现故障时,Eureka就会转入自动保护模式,它允许分片故障期间继续提供服务的发现和注册,当故障分片恢复正常时,集群中其他分片会把他们的状态再次同步回来。

2.  客户端组件包含服务消费者和服务提供者。在应用程序运行中,Eureka客户端向注册中心自身提供的服务并周期性的发送心跳来更新它的服务租约,同时也可以从服务端查询当前注册的服务信息并把他们缓存到本地并周期性的刷新服务状态。

Eureka原理

Region和Zone的关系

 

Application Service 就相当于本书中的服务提供者(用户微服务),application client就相当于本书中的服务消费者(电影微服务)。

make remote call,可以简单理解为调用RESTful的接口。

us-east-1c、us-east-1dd等是Zone,它们都属于es-east-1这个region;

由图可知,eureka包含两个组件:Eureka Server和Eureka Client。

Eureka Server提供服务注册服务,各个节点启动后,会在Eureka Server中进行注册,这样Eureka Server中服务注册表中将会存储所有可用服务节点的信息,服务节点的信息可以在界面中直观的看到。

Eureka Client是一个Java客户端,用于简化与Eureka Server的交互,客户端同时也具备一个内置的、使用轮询(round-robin)负载算法的负载均衡器。

在应用启动后,将会向Eureka Server发送心跳(默认周期为30秒)。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,Eureka Server将会从服务注册表中把这个服务节点移除(默认90秒)。

Eureka Server之间将会通过复制的方式完成数据的同步。

Eureka还提供了客户端缓存的机制,即使所有的Eureka Server都挂掉,客户端依然可以利用缓存中的信息消费其他服务的API。

实现Eureka Server

将Eureka Server和Eureka Client放到同一个moduls中,这个大pom.xml作为配置管理其他Server和client。

大pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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.kevin.cloud</groupId>

   <artifactId>microservice-spring-cloud</artifactId>

   <version>0.0.1-SNAPSHOT</version>

   <packaging>pom</packaging>

   
   <modules>

      <module>microservice-consumer-movie</module>

      <module>microservice-provider-user</module>

      <module>microservice-discovery-eureka</module>

   </modules>


   <properties>

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

      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <java.version>1.8</java.version>

   </properties>


   <parent>

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

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

      <version>1.4.1.RELEASE</version>

   </parent>


   <dependencyManagement>

      <dependencies>

         <dependency>

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

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

            <version>Camden.SR1</version>

            <type>pom</type>

            <scope>import</scope>

         </dependency>

      </dependencies>

   </dependencyManagement>


   <build>

      <plugins>

         <plugin>

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

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

         </plugin>

      </plugins>

   </build>


</project>

pom.xml

<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>


    <parent>

        <groupId>com.kevin.cloud</groupId>

        <artifactId>microservice-spring-cloud</artifactId>

        <version>0.0.1-SNAPSHOT</version>

        <relativePath/>

    </parent>


    <artifactId>microservice-discovery-eureka</artifactId>

    <packaging>jar</packaging>


    <properties>

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

        <java.version>1.8</java.version>

    </properties>


    <dependencies>

        <!-- Eureka的依赖包 -->

        <dependency>

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

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

        </dependency>

        <!-- 安全模块 -->

        <dependency>

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

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

        </dependency>

    </dependencies>


</project>

application.yml

security:

  basic:

    enabled: true

  user:

    name: kevin

    password: 123456

server:

  port: 8761  #指定服务端口

eureka:

  client:

    healthcheck:

      enabled: true

    register-with-eureka: false #是否将eureka自身作为应用注册到eureka注册中心

    fetch-registry: false  #为true时,可以启动,但报异常caonot execute request on any know server

    service-url:

      defaultZone: http://kevin:123456@localhost:8761/eureka

EurekaApplication.java

package com.kevin.cloud;



import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

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



/**

 *

 * @title   EurekaServer注册中心

 * @description

 * @author caonanqing

 * @createDate 2018/11/7

 * @version 1.0

 */

@SpringBootApplication  //设为springboot

@EnableEurekaServer     //实现服务发现,注册

public class EurekaApplication {


    public static void main(String[] args) {

        SpringApplication.run(EurekaApplication.class, args);

        System.out.println("EurekaServer启动...");

    }


}

实现Eureka Client(提供者)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>


   <artifactId>microservice-provider-user</artifactId>

   <packaging>jar</packaging>


   <name>microservice-provider-user</name>

   <description>Demo project for Spring Boot</description>


   <parent>

      <groupId>com.kevin.cloud</groupId>

      <artifactId>microservice-spring-cloud</artifactId>

      <version>0.0.1-SNAPSHOT</version>

      <relativePath/>

   </parent>


   <properties>

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

      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <java.version>1.8</java.version>

   </properties>


   <dependencies>

      <dependency>

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

         <artifactId>spring-boot-starter-data-jpa</artifactId>

      </dependency>

      <dependency>

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

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

      </dependency>

      <dependency>

         <groupId>com.h2database</groupId>

         <artifactId>h2</artifactId>

         <scope>runtime</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>


</project>

application.yml

server:

  port: 7900

spring:

  jpa:

    generate-ddl: false

    show-sql: true

    hibernate:

      ddl-auto: none

  datasource:

    platform: h2

    schema: classpath:schema.sql

    data: classpath:data.sql

  application:

    name: microservice-provider-user

logging:

  level:

    root: INFO

    org.hibernate: INFO

    org.hibernate.type.descriptor.sql.BasicBinder: TRACE

    org.hibernate.type.descriptor.sql.BasicExtractor: TRACE

    com.cloud: DEBUG

eureka:

  client:

    #注册中心地址

    service-url:

      defaultZone: http://kevin:123456@localhost:8761/eureka/

  #instance:

    #prefer-ip-address: true

    #instance-id: ${spring.application.name}:${spring.application.instance_id:${server.port}}

schema.sql

drop table if exists user;

create table user(

  id int not null auto_increment,

  username varchar(40),

  name varchar(20),

  age int(3),

  balance decimal (10,2),

  primary key(id)

);

data.sql

insert into user(id,username,name,age,balance) values(1,'user1','张三',20,100.00)

insert into user(id,username,name,age,balance) values(2,'user2','李四',20,100.00)

insert into user(id,username,name,age,balance) values(3,'user3','王五',20,100.00)

insert into user(id,username,name,age,balance) values(4,'user4','马六',20,100.00)

MicroserviceSimpleProviderUserApplication .java

package com.keivn.cloud;


import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

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

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;


/**

 *

 * @title   服务提供者

 * @description

 * @author caonanqing

 * @createDate 2018/11/7

 * @version 1.0

 */

@SpringBootApplication

@EnableEurekaClient

public class MicroserviceSimpleProviderUserApplication {

   public static void main(String[] args) {

      SpringApplication.run(MicroserviceSimpleProviderUserApplication.class, args);

      System.out.println("服务提供者启动...");

   }

}

UserController.java

package com.keivn.cloud.controller;

import com.keivn.cloud.entity.User;

import com.keivn.cloud.repository.UserRepository;

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.GetMapping;

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

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

import com.netflix.appinfo.InstanceInfo;

import com.netflix.discovery.EurekaClient;


/**

 *

 * @title

 * @description

 *  作用:

 *  1:测试服务实例的相关内容

 *  2:为后来的服务做提供

 * @author caonanqing

 * @createDate 2018/11/6

 * @version 1.0

 */

@RestController

public class UserController {

    @Autowired

    private UserRepository userRepository;

    @Autowired

    private EurekaClient eurekaClient;

    @Autowired

    private DiscoveryClient discoveryClient;

    @GetMapping("/simple/{id}")

    public User findById(@PathVariable Long id ){

        return this.userRepository.findOne(id);

    }

    @GetMapping("/eureka-instance")

    public String serviceUrl() {

        InstanceInfo instanceInfo = this.eurekaClient.getNextServerFromEureka("MICROSERVICE-PROVIDER-USER", false);

        return instanceInfo.getHomePageUrl();

    }

    @GetMapping("/instance-info")

    public ServiceInstance showInfo(){

        ServiceInstance localServiceInstance = this.discoveryClient.getLocalServiceInstance();

        return localServiceInstance;

    }

}

User.java

package com.keivn.cloud.entity;

import javax.persistence.*;

import java.io.Serializable;

import java.math.BigDecimal;

/**

 *

 * @title

 * @description

 * @author caonanqing

 * @createDate 2018/11/6

 * @version 1.0

 */

@Entity

public class User implements Serializable {


    @Id

    @GeneratedValue(strategy = GenerationType.AUTO)

    private Long id;

    @Column

    private String username;

    @Column

    private String name;

    @Column

    private Short age;

    @Column

    private BigDecimal balance;

    public User() {

    }

    public User(String username, String name, Short age, BigDecimal balance) {

        this.username = username;

        this.name = name;

        this.age = age;

        this.balance = balance;

    }

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public Short getAge() {

        return age;

    }

    public void setAge(Short age) {

        this.age = age;

    }

    public BigDecimal getBalance() {

        return balance;

    }

    public void setBalance(BigDecimal balance) {

        this.balance = balance;

    }

}

UserRepository.java

package com.keivn.cloud.repository;


import com.keivn.cloud.entity.User;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.stereotype.Repository;


/**

 *

 * @title

 * @description

 * @author caonanqing

 * @createDate 2018/11/6

 * @version 1.0

 */

@Repository

public interface UserRepository extends JpaRepository<User, Long> {

}

Eureka Client(消费者)

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<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>

   <artifactId>microservice-consumer-movie</artifactId>

   <packaging>jar</packaging>

   <parent>

      <groupId>com.kevin.cloud</groupId>

      <artifactId>microservice-spring-cloud</artifactId>

      <version>0.0.1-SNAPSHOT</version>

      <relativePath/>

   </parent>

   <properties>

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

      <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

      <java.version>1.8</java.version>

   </properties>

   <dependencies>

      <dependency>

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

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

      </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>

</project>

application.yml

server:

  port: 7901

user:

  userServicePath: http://localhost:7900/simple/

spring:

  application:

    name: microservice-consumer-movie

eureka:

  client:

    healthcheck:

      enabled: true

    service-url:

      defaultZone: http://kevin:123456@localhost:8761/eureka

  instance:

    prefer-ip-address: true

EurekaClientApplication.java

package com.keivn.cloud;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

import org.springframework.context.annotation.Bean;

import org.springframework.web.client.RestTemplate;


/**

 *

 * @title   服务消费者

 * @description

 * @author caonanqing

 * @createDate 2018/11/7

 * @version 1.0

 */

@SpringBootApplication

@EnableEurekaClient    //注册到Eureka

public class MicroserviceSimpleConsumerUserApplication {


   @Bean

   public RestTemplate restTemplate(){

      return new RestTemplate();

   }

   public static void main(String[] args) {

      SpringApplication.run(MicroserviceSimpleConsumerUserApplication.class, args);

      System.out.println("服务消费者启动...");

   }

}

MovieController.java

package com.keivn.cloud.controller;


import com.keivn.cloud.entity.User;

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

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

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

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

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

import org.springframework.web.client.RestTemplate;


/**

 *

 * @title

 * @description

 * @author caonanqing

 * @createDate 2018/11/7

 * @version 1.0

 */

@RestController

public class MovieController {


    @Autowired

    private RestTemplate restTemplate;


    @Value("${user.userServicePath}")

    private String userServicePath;


    @GetMapping(value = "/movie/{id}")

    public User finById(@PathVariable long id ){

        return this.restTemplate.getForObject(this.userServicePath + id, User.class);

    }

}

User.java

package com.keivn.cloud.entity;


import java.io.Serializable;

import java.math.BigDecimal;


/**

 *

 * @title

 * @description

 * @author caonanqing

 * @createDate 2018/11/7

 * @version 1.0

 */

public class User implements Serializable {

    private Long id;

    private String username;

    private String name;

    private Short age;

    private BigDecimal balance;

    public User() {

    }

    public User(Long id, String username, String name, Short age, BigDecimal balance) {

        this.id = id;

        this.username = username;

        this.name = name;

        this.age = age;

        this.balance = balance;

    }

    public Long getId() {

        return id;

    }

    public void setId(Long id) {

        this.id = id;

    }

    public String getUsername() {

        return username;

    }

    public void setUsername(String username) {

        this.username = username;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public Short getAge() {

        return age;

    }

    public void setAge(Short age) {

        this.age = age;

    }

    public BigDecimal getBalance() {

        return balance;

    }

    public void setBalance(BigDecimal balance) {

        this.balance = balance;

    }

}
 

 

猜你喜欢

转载自blog.csdn.net/qq1021979964/article/details/83859416
今日推荐