Service discovery and registration and Eureka

A Spring Cloud Features

# Convention over configuration

# Out of the box, Quick Start

# Suitable for a variety of environments and can be deployed in a PC server or cloud environment

# Lightweight components

# Support components is very rich, full-featured

# Neutral selection

 

Two service providers and service consumers

 

Three service discovery and registration

Why do you need service registration and discovery

IP address change or upgrade the service is restarted after #

Changes # scalable service instance level

# With a node running multiple service

It requires a registration mechanism to help us to get a response.

 

The core mechanisms:

Examples of registration information to the registry

The caller lookup service through the registry

Examples of the caller access to services list

The caller through load balancing communication

 

3.1 Basic Process

 

 

 

First of all: service consumers and service discovery component registrants to register with the service

Second: When to call the service consumer will be queried from service discovery component

 

 

demand:

# Each instance of a service will start when released by remote API HTTP / REST or Thrift, etc.

# Server instances of a specific number and location of the dynamic will change

# Virtual machine and container will usually be assigned a dynamic IP address

 

 

Functions 3.2 service discovery component

# Service Registry: a record in the database is currently available network information service instance, is the core of the service discovery mechanism. Provide service registry query API and Management API, use the API to obtain the services available instance, use the management API for the registration and deregistration.

# Service Registration

# health examination

 

3.3 way service discovery

3.3.1 client discovery

Its main feature is the client decides to network location service instances and request load balancing. Client queries the service registry (the database of available service instances), load-balancing algorithm to select one instance and request. Eureka typical or ZK

 

Advantages and disadvantages of client discovery mode

advantage:

It does not require a lot of network hops

Disadvantages:

The client and service registry coupling

We need to build a client for the application of each programming language, framework and other discovery logic, such as Netflix Prana to provide a non-JVM client HTTP-based proxy service discovery scheme

 

# Server discovery

Sending a request to a service, the client sends a request to the operating position by a known router or a load balancer. They will query the service registry, and to forward the request to the service instance is available. Typical Consul + Nginx

 

 


Server discovery mode advantages and disadvantages:

advantage:

Clients need to implement discovery, only you need to router or load balancer can send a request

Disadvantages:

Unless it becomes part of a cloud environment, or the routing mechanism must be installed and configured as the other system components. In order to achieve a certain degree of availability and access capabilities, we also need to configure a certain number of copies.

Compared to client discovery, server discovery mechanism requires more network hops.

 

3.4 service discovery component Eureka

3.4.1 What is Eureka

 

Eureka is a service discovery frame Netflix development, is itself a REST-based services, the intermediate layer is mainly used for positioning operation AWS service domain to achieve load balancing and failover intermediate layer service purposes. Spring Cloud integrate it in other subprojects spring-cloud-netflix in order to achieve spring cloud service discovery.

 

3.4.2 Eureka principle

AWS first need to understand a few concepts:

Region: AWS cloud services in different data centers around the world places, such as North America, South America, Europe and Asia. Correspondingly, based on the geographic location of our infrastructure services in an area known as a collection area. It is independent between different regions. Plainly room is similar in different places.

Available Zone: background made based disaster recovery, simply, is a different region of the same area of ​​the room

 

# First registration service to Eureka

# 30s every heartbeat sent to re-lease, the lease if the client can not be updated many times, it is removed from the server registration center in the 90s.

# Registration information and updates will be replicated to other nodes Eureka, client families from any area can be found to the registry information, occurs once every 30s copied to locate their services, and remote calls

# The client can also cache some of the information service instances, even a full hang Eureka, the client can also navigate to the service address

 

 

 


3.4.3 build Euraka Server

First of all: to build parent project

<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>

 

      <modules>

           <module>microservice-consumer</module>

           <module>microservice-provider</module>

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

      </modules>

      <groupId>com.microservice</groupId>

      <artifactId>microservice</artifactId>

      <version>1.0-SNAPSHOT</version>

      <packaging>pom</packaging>

 

      <parent>

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

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

           <version>1.5.6.RELEASE</version>

      </parent>

 

      <dependencyManagement>

           <dependencies>

                 <dependency>

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

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

                      <version>Dalston.SR3</version>

                      <type>pom</type>

                      <scope>import</scope>

                 </dependency>

           </dependencies>

      </dependencyManagement>

      <dependencies>

           <dependency>

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

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

           </dependency>

           <dependency>

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

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

           </dependency>

 

           <dependency>

                 <groupId>mysql</groupId>

                 <artifactId>mysql-connector-java</artifactId>

                 <version>5.1.44</version>

           </dependency>

      </dependencies>

      <build>

           <finalName>${project.artifactId}</finalName>

           <plugins>

                 <! - resource file copy plug-in ->

                 <plugin>

                      <groupId>org.apache.maven.plugins</groupId>

                      <artifactId>maven-resources-plugin</artifactId>

                      <configuration>

                            <encoding>UTF-8</encoding>

                      </configuration>

                 </plugin>

                 <-! Java compiler plug-ins ->

                 <plugin>

                      <groupId>org.apache.maven.plugins</groupId>

                      <artifactId>maven-compiler-plugin</artifactId>

                      <configuration>

                            <source>1.8</source>

                            <target>1.8</target>

                            <encoding>UTF-8</encoding>

                      </configuration>

                 </plugin>

                 <plugin>

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

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

                 </plugin>

           </plugins>

           <pluginManagement>

                 <plugins>

                      <! - Configure tomcat plug-ins ->

                      <plugin>

                            <groupId>org.apache.tomcat.maven</groupId>

                            <artifactId>tomcat7-maven-plugin</artifactId>

                            <version>2.2</version>

                      </plugin>

                 </plugins>

           </pluginManagement>

      </build>

</project>

 

Second: build Euraka Server

<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.0http://maven.apache.org/xsd/maven-4.0.0.xsd">

      <modelVersion>4.0.0</modelVersion>

      <packaging>war</packaging>

 

      <parent>

           <artifactId>microservice</artifactId>

           <groupId>com.microservice</groupId>

           <version>1.0-SNAPSHOT</version>

      </parent>

 

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

 

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

           </dependency>

      </dependencies>

</project>

 

Then: application.yml configuration file in the application.xml

security:

  basic:

    enabled: true

  user:

    name: user

    password: password

server:

  port: 8761

eureka:

  client:

    register-with-eureka: false

    fetch-registry: false

    service-url:

      defaultZone:http://user:password@localhost:8761/eureka

 

   

Last: Creating EurekaApplication, and add @SpringBootApplication

@EnableEurekaServer

public class EurakaApplication{

      public static void main(String[] args) throws Exception {

           SpringApplication.run(EurakaApplication.class, args);

      }

 

}

 

You can start the Eureka Server

3.4 micro-services registered to Eureka

First: Eureka confirm whether the introduction of the relevant configuration maven current environment, and add the following dependent

           <dependency>

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

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

           </dependency>

Second: add on the micro-class service starts @EnableEurekaClient notes, making him a Eureka Client, to register with the Eureka Server at boot time.

Then: in the application configuration file application.yml micro-services, we do not add the following configuration, because it means that the server, client we need to Eureka registration

eureka:

  client:

    register-with-eureka: false

fetch-registry: false

You should be able to have health checks and configuration path configuration

eureka:

  client:

    healthcheck:

      enabled: true

    service-url:

      defaultZone:http://nicky:123abcABC@localhost:8761/eureka

Finally: Adding @EnableEurekaClient annotation startup class, this class represents the Eureka can be used as a client, you can register to Eureka after start

@SpringBootApplication

@EnableEurekaClient

public class UserServiceRunner{

      public static void main(String[] args) throws Exception {

           SpringApplication.run(UserServiceRunner.class, args);

      }

}

 

3.5 Eureka configuration items

eureka.client.allow-redirects: whether to allow a client request to redirect Eureka or other backup servers, the default is fasle

eureka.client.eureka-connection-idle-timeout-seconds: HTTP server connected to the eureka can remain idle time (a few seconds) before closing.

eureka.client.eureka-server-connect-timeout-seconds: Eureka server indicates that the connection, to wait long time out

eureka.client.eureka-server-port: Eureka Server end opening

eureka.client.eureka-server-dns-name: Obtain DNS name to query the server for a list of eureka.

eureka.client.eureka-server-read-timeout-seconds: shown prior to reading data from the server eureka wait time (in seconds)

eureka.client.eureka-server-total-connections: eureka from the client to the total number of connections allowed all eureka server.

eureka.client.eureka-server-total-connections-per-host: the host is provided for each allowed number of connections to the Eureka Server

eureka.client.fetch-registry: whether to allow the client to get information to the registry Eureka, general server is set to false, the client is set to true

eureka.client.register-with-eureka: whether to allow registration information to Eureka Server, default true, if it is a server-side, it should be set to false

eureka.client.fetch-remote-regions-registry: a comma-separated list area, the registration information for acquiring eureka

eureka.client.g-zip-content: if the data acquired from the server need to be compressed

eureka.client.prefer-same-zone-eureka: whether preferentially selected the same Zone instance, the default is true

eureka.client.registry-fetch-interval-seconds: How long will get a registry data from Eureka Server, default 30s

eureka.client.service-url: available area mapping, fully qualified url listed eureka communicate with the server. Each value may be a URL, or may be a comma-separated list of alternative locations.

eureka.dashboard.enabled: Eureka Home is enabled, the default is true

eureka.dashboard.path: The default is /

eureka.instance.appname: name of the application in eureka registered.

eureka.instance.app-group-name: Group name of the application in eureka registered

eureka.instance.health-check-url: Health Check absolute path

eureka.instance.health-check-url-path: a relative path health check

eureka.instance.hostname: Setting the host name

eureka.instance.instance-id: id instance setting register

eureka.instance.lease-expiration-duration-in-seconds: set how long the lease means that, by default 90

eureka.instance.lease-renewal-interval-in-seconds: Eureka represent client needs to send a heartbeat to the server eureka frequency (in seconds) to show that it still exists. If within the period specified did not receive a heartbeat leaseExpirationDurationInSeconds

eureka.instance.metadata-map: Metadata may be provided

eureka.instance.prefer-ip-address: instance name to IP, but it is recommended hostname, default is false

 

Four load balancing

4.1 Ribbon presentation and architecture

Load balancing, we can do load balancing server and client. Server load balancing, for example, can use Nginx. The client load balancing to do, is have a client component, to know what's available to micro-services, to implement a load balancing algorithm.

 

Ribbon workflow is divided into two steps:

First: first select Eureka Server, in one preferred less load and Zone Server;

Second: then according to user-specified policy, and then take from the server to the list of services, select a registered address. Ribbon which provides a variety of strategies, such as polling round bin, the Random Random, weighted according to the response time.

 

 


4.2 Ribbon for load balancing

4.2.1 Basic Usage

To use the Ribbon load balanced, then we need to introduce corresponding dependent, if you have because if Eureka dependence, there is no need to introduce the Ribbon dependency again.

           <dependency>

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

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

           </dependency>

Then add comment @LoadBalanced on startup class, the load balancing effect.

@SpringBootApplication

@EnableEurekaClient

public classMovieServiceRibbonRunner {

      @Bean

      @LoadBalanced

      public Rest Rest Template Template () {

           return new RestTemplate();

      }

 

      public static void main(String[] args) {

           SpringApplication.run(MovieServiceRibbonRunner.class, args);

      }

}

 

We can modify the properties application.yml instance_id file:

eureka:

  client:

    healthcheck:

      enabled: true

    service-url:

      defaultZone:http://nicky:123abcABC@localhost:8761/eureka

  instance:

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

 

Consumers Controller, access a virtual ip, that is the name of our micro services

@RestController

public class MovieController {

     

      @Autowired

      private rest Rest Template template;

     

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

      public User findById(@PathVariable Long id) {

 

           returnthis.restTemplate.getForObject("http://microservice-provider-user/user/"+id, User.class);

      }

}

 

The last two starts service provider instance, you can modify the port achieved.

4.2.2 Configuration Ribbon by custom code

First, the class need to add @Configuration comment, but note that, if coupled with this comment, he could not contain the specified comment @ComponentScan package or @SpringBootApplication scan path.

@Configuration

public classRibbonTestConfiguration {

      @Autowired

      IClientConfig config;

     

      @Bean

      public IRuleribbonRule(IClientConfig config){

           return new RandomRule();

      }

}

Second: plus @RibbonClient comment on startup class, specify the name and file type configuration

@SpringBootApplication

@EnableEurekaClient

@RibbonClient(name="microservice-provider-user",configuration=RibbonTestConfiguration.class)

public classMovieServiceRunner {

      @Bean

      @LoadBalanced

      public Rest Rest Template Template () {

           return new RestTemplate();

      }

 

      public static void main(String[] args) {

           SpringApplication.run(MovieServiceRunner.class, args);

      }

}

 

4.2.3 configuration file custom Ribbon

That we can be configured through yml or properties configuration file, then use the options we configured.

Note: Here are some issues in order of priority:

Profile defines a priority greater than a priority greater than the Java code using the spring @RibbonClient default priority

It supports the following attributes:

NFLoadBalancerClassName: should implement ILoadBalancer

NFLoadBalancerRuleClassName: should implement IRule

NFLoadBalancerPingClassName: should implement IPing

NIWSServerListClassName: should implement ServerList

NIWSServerListFilterClassName: should implement ServerListFilter

 

application.yml configured as follows:

microservice-provider-user:

  ribbon:

    NFLoadBalancerRuleClassName:com.netflix.loadbalancer.RandomRule

 

Five Feign (declarative REST Client)

5.1 Introduction and Basics

Feign web service client is a declarative, it makes writing web services client easier. Using Feign create an interface and annotate it. It has support for pluggable annotations, including Feign your own notes and comments jax-rs. Feign also pluggable an encoder and a decoder. Spring Cloud adds support for Spring MVC annotations, and use the same HttpMessageConverters used in the Spring Web by default. Spring Cloud integrates Ribbon and inspiration, provides load balancing http client in use.

 

Feign added depends to Maven

<dependency>

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

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

</dependency>

Then create the interface, and add annotations @EnableFeignClients

@SpringBootApplication

@EnableEurekaClient

@EnableFeignClients

public classMovieServiceRunner {

      public static void main(String[] args) {

           SpringApplication.run(MovieServiceRunner.class, args);

      }

}

 

Portrait positive interface to call other micro services to apply for this call

Create an interface:

First, add annotations @FeignClient interface, specify the name of the service you need to call the micro

Second: If the startup time, suggesting Http Method is not correct that we need to use before the old notes, namely:

@RequestMapping (method = RequestMethod.GET, value = "/ user / {id}"), can not be used:

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

 

Then: If prompted PathVariableannotation was empty on param 0, then we need to:

 

There is: micro service providers and consumers on both sides of the HTTP method must be consistent with the best, if one side is a GET request, the other side is a POST request, there will be an error. And if a load is passed to the object, even if the specified request is GET, POST request also a general practice that the object is not transmitted, but a single pass parameters

For example @ReqquestParam ( "name") String name, @ ReqquestParam ( "age") int age like

 

public UserfindById (@PathVariable ( "id") Long id); instead:

public UserfindById (@PathVariable Long id); can

This is equivalent to pit it is Feign

@FeignClient("microservice-provider-user")

public interface UserFeignClient {

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

      public User findById(@PathVariable Long id);

}

 

Then in the other classes you can call:

@RestController

public class MovieController {

 

      @Autowired

      private UserFeignClient userFeignClient;

 

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

      public User findById(@PathVariable Long id) {

 

           return userFeignClient.findById(id);

      }

}

 

5.2 configuration override Feign

Spring Cloud allows you complete control over Feign client by declaring some additional notes that @FeignClient (name = "stores", configuration = FooConfiguration.class)

 

In general, we do not need to be used on custom FooConfiguration @Configuration components used, if we need to use it, or from the group consisting @ComponentScan @SpringBootApplication annotation scanned package excluded. Ribbon and similar.

 

Suppose we now define a Configuration1 this class, use the default feign contract, instead of using SpringMvcContract, namely:

@Configuration

public class Configuration1 {

      @Bean

      public ContractfeignContract() {

 

           return newfeign.Contract.Default();

      }

}

Then Feign at the interface of the specified configuration @FeignClient, rewrite the configuration using just defined Configuration1, namely:

@FeignClient(name="microservice-provider-user",configuration=Configuration1.class)

public interface UserFeignClient {

 

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

      public User findById(@PathVariable("id") Long id);

}

But here we still use the SpringMVC notes, GetMapping, although there is no error, but will start when the error. For example java.lang.IllegalStateException: MethodfindById not annotated with HTTP method type (. Ex GET, POST)

So, we at the interface should be replaced Feign own comments.

@FeignClient(name="microservice-provider-user",configuration=Configuration1.class)

public interface UserFeignClient {

 

      @RequestLine("GET /user/{id}")

      public User findById(@Param("id") Long id);

}

 

 

Feign support request response GZIP Compression:

feign.compression.request.enabled=true

feign.compression.response.enabled=true

 

5.3 feign log

Feign default log level is DEBUG level.

@Bean

Logger.Level feignLoggerLevel(){

      return Logger.Level.FULL;

}

 

Six solutions to common problems

6.1 Eureka environment and the cloud configuration

Eureka can run on AWS AWS environment and non-environment, Eureka can also be run in test and production environments.

If you need to run on the AWS environment, you need to specify run by -Deureka.datacenter = cloud on AWS, in yml we can eureka.datacenter: cloud specified.

eureka.datacenter:cloud

If you need to run a test or production environment, we need to be specified by -Deureka.environment. If you specify a test environment eureka.environment: test, if you are running in a production environment, specify eureka.environment: product

 

6.2 self-protection tips

 

6.3 Eureka how to solve the problem of slow registration services

As examples further relates to a periodic heartbeat registry, the default duration is 30 seconds (by serviceUrl). Prior to have the same metadata in the local cache example, servers, clients, client service is available for discovery (3 beats may be required). You can use eureka.instance.leaseRenewalIntervalInSeconds configuration, which will speed up the process of the client to connect to other services.

In production, it is best to stick with the default value, because there are some inside the server computing, they make assumptions about renewal.

 

How to solve Eureka Server 6.4 is not kicked out of the question node has been shut down

Service-Terminal:

# Disable self-protection

eureka.server.enable-self-preservation:false

# Reduce cleanup interval (in milliseconds, the default is 60 * 1000)

eureka.server.eviction-interval-timer-in-ms:  5000

 

Client:

Open health check (required spring-boot-starter-actuator-dependent)

eureka.client.healthcheck.enabled= true    

Lease update interval (default 30 seconds)

eureka.instance.lease-renewal-interval-in-seconds=10

Lease expiration time (default 90 seconds)

eureka.instance.lease-expiration-duration-in-seconds=30

 

6.5 Eureka HA configuration (assuming three nodes)

6.5.1 Add the following configuration in the hosts file

127.0.0.1 Peer1

127.0.0.1  peer2

127.0.0.1 peer3

 

6.5.2 add the following configuration in application.yml

---

spring:

  profiles: peer1

  application:

    name: EUREKA-HA

server:

  port: 8761

eureka:

  instance:

    hostname: peer1

  client:

    ServiceUrl:

      defaultZone:http://peer2:8762/eureka/,http://peer3:8763/eureka/

---

spring:

  profiles: peer2

  application:

    name: EUREKA-HA

server:

  port: 8762

eureka:

  instance:

    hostname: peer2

  client:

    ServiceUrl:

      defaultZone:http://peer1:8761/eureka/,http://peer3:8763/eureka/

---

spring:

  profiles: peer3

  application:

    name: EUREKA-HA

server:

  port: 8763

eureka:

  instance:

    hostname: peer3

  client:

    ServiceUrl:

      defaultZone:http://peer1:8761/eureka/,http://peer2:8762/eureka/


----------------
Disclaimer: This article is CSDN blogger original article "happy19870612" of.
This paper is mainly used for collection of science, thanks happy19870612 provided

Guess you like

Origin www.cnblogs.com/yscec/p/11583416.html