Springcloud Micro Service---Service Registration and Discovery (Eureka)

Source: Internet
Author: User

introduction of Spring Cloud
Spring Cloud is based on Springboot, providing developers with tools to quickly build distributed systems, including configuration management, service discovery, circuit breakers, routing, micro-proxies, event busses, global locks, decision-making campaigns, distributed sessions, and more.

Second, create the Service registration center
Here we need to use the components on spring Cloud Netflix Eureka, Eureka is a service registration and Discovery module.

Eureka:

is a pure servlet application that needs to be built into a war package deployment
Using the Jersey framework to implement its own RESTful HTTP interface
Synchronization between peers and registration of services are all implemented via HTTP protocol
Timed tasks (sending heartbeat, timed cleanup expiration service, node synchronization, etc.) implemented by a timer that comes with the JDK
Memory cache is implemented using Google's guava package
2.1 First create a MAVEN master project.
2.2 Then create 2 model projects: One model project as a service registry, Eureka Server, and the other as Eureka Client
To create a process:

Right-click Project-Create model-> Select spring Initialir such as:
Image

Click "Next" and enter the corresponding name, for example:

Click "Next", select "Cloud Discovery" and select "Eureka Server", such as:

Click "Next", select Save path, then click "Finish"
The Pom.xml file for the completed project is as follows (Maven creates the package structure POM etc, please go to the project to see):

<?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" >
<parent>
<artifactId>springcloud-zureka</artifactId>
<groupId>com.spring.cloud.zureka</groupId>
<version>0.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>springcloud-zureka-server</artifactId>
<packaging>jar</packaging>

<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.cl Oud</groupid> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency>& lt;/dependencies><build> <finalName>${artifactId}</finalName> <plugins> <plugin > <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-maven-plu gin</artifactid> </plugin> <plugin> <groupId>org.apache.maven.plugins<                /groupid> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${java.version}</souRce> <target>${java.version}</target> <testsource>${java.version}</t        Estsource> <testTarget>${java.version}</testTarget> </configuration> </plugin> </plugins></build>

</project>
2.3 Starting a Service registration center
Only one annotation @enableeurekaserver is required, and this annotation needs to be added on the startup application class of the Springboot project:

/**

    • @Author Lixinhao
    • @Description
    • @Date 2018/4/13 17:25br/>*/
      @EnableEurekaServer

      public class Eurekaserverapplication {

      public static void Main (string[] args) {
      Springapplication.run (Eurekaserverapplication.class, args);
      }
      }
      2.4 APPICATION.YML Configuration
      Eureka is a highly available component that does not have a back-end cache, each instance is registered to send a heartbeat to the registry (so it can be done in memory), and by default Erureka server is also a Eureka client, and you must specify a server. Eureka Server configuration file Appication.yml:

#配置eureka端口, the port must be independent
Server
port:8761

Eureka
Instance
#配置主机名
Hostname:localhost
Client
#配置服务注册中心是否以自己为客户端进行注册 (config false)
Registerwitheureka:false
#是否取得注册信息 (config false)
Fetchregistry:false
Serviceurl:
#配置eureka服务地址
defaultzone:http://${eureka.instance.hostname}:${server.port}/eureka/
by Eureka.client.registerWithEureka:false and Fetchregistry:false to show that you are a Eureka server

2.5 Log Configuration
Create configuration file Bootstrap.yml:

#日志
Logging
Config:classpath:logback-spring.xml
path:e:/log/@[email protected]
Create configuration file Logback-spring.xml:

%d{yyyy-mm-dd HH:mm:ss. SSS}%-5level---[%thread]%logger{50}:%msg%n ${log_path}/info.log ${log_path}/info-%d{yyyymmdd}-%i.log 10MB %d{yyyy-mm-dd HH:mm:ss. SSS}%-5level---[%thread]%logger{50}:%msg%n ERROR ${log_path}/error.log ${log_path}/error-%d{yyyymmdd}-%i.log 500MB 2 %d{yyyy-mm-dd HH:mm:ss. SSS}%-5level---[%thread]%logger{50}:%msg%n **2.6 View interface Information **eureka Server is interface, start the project, open browser access: http://localhost:8761, the interface is as follows: No instances available no service was found, next create service * * Three, Create a service provider (Eureka client) * * When the client registers with the server, it provides some metadata, such as host and Port, URL, home page, and so on. Eureka server receives heartbeat messages from each client instance. If the heartbeat times out, the instance is typically removed from the registration server. The creation process is similar to the server, and the Pom.xml is created as follows: Springcloud-zureka com.spring.cloud.zureka 0.0.1 4.0.0 Springcloud-zureka-client Jar UTF-8 UTF-8 1.8 org.springframework.cloud spring-cloud-starter-eureka org.springframework.boot Spring-boot-starter-web ${artifactid} org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-compiler-plugin ${java.version} ${java.version} ${java.version} ${java.version} By annotating @enableeurekaclient You are a Eureka client./** * @Author Lixinhao * @Description * @Date 2018/4/13 17:25 * * @EnableEureka Client@springbootapplication@restcontrollerpublic class Eurekaclientapplication {public static void main (string[] args) {Springapplication.run (eurekaclientapplication.class, args);} @Value ("${server.port}") String port; @RequestMapping ("/hi") Public String Home (@RequestParam String name) {return ' Hi ' +name+ ', I am from port: ' +port;}} In the configuration file, specify the address of your service registry, the APPLICATION.YML configuration file is as follows: Eureka:client:serviceUrl: #配置eureka服务地址, link to the registry address defaultzone:http:// Localhost:8761/eureka/server:port:8762spring:application: #在注册中心显示的 "Application" Name: "@[email protected]Note: The @ is used in the Spring.application.name[email protected], in the Yml file need to add single quotation marks or double quotation marks, otherwise cannot get the value needs to indicate spring.application.name, this is very important, this is in the future between service and service calls are generally based on this name. Start the project, open the http://localhost:8761, the Eureka Server URL: You will find a service has been registered in the service, the service name is Springcloud-zureka-client, the port is: 8762** four, Eureka Self-protection mode * * If you see this hint on the first page of Eureka Server, the Eureka has entered the protected mode: emergency! EUREKA may incorrectly claiming INSTANCES is up when the they ' RE not. Renewals is LESSER THAN THRESHOLD and HENCE the INSTANCES is not BEING EXPIRED JUST to be SAFE. Cause: When Eureka server is running, it Statistics the ratio of heartbeat failure within 15 minutes is less than 85%, if there is less than the situation (in the case of single-machine debugging is easy to meet, the actual production environment is usually due to network instability), Eureka server will be the current instance registration information protection, and prompted this warning. Protected mode is primarily used for protection in a network partition scenario between a group of clients and Eureka Server. Once in protected mode, Eureka server will attempt to secure the information in its service registry, eliminating the data in the service registry (that is, not logging off any microservices) Workaround: 1. Eureka Server side: Configure the time interval to turn off self-protection and configure Eureka server to clean up invalid nodes on demand. > Eureka.server.enable-self-preservation # Set to False to turn off self-protection > Eureka.server.eviction-interval-timer-in-ms # Cleanup interval (in milliseconds, default is 60*1000) 2. Eureka Client Side: Configure open Health Check and configure renewal update time and expiry time > Eureka.client.healthcheck.enabled # on Demand # Open Health Check (requires Spring-boot-starter-actuator dependent) > Eureka.instance.lease-renewal-interval-in-seconds # Renewal interval (default 30 seconds) > Eureka.instance.lease-expiration-duration-in-seconds # Renewal Expiry time (default 90 seconds) The production environment recommends a default configuration, and the service stops to the registry to clean up the instances with some calculations. ****

Springcloud---Service registration and Discovery (Eureka)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.