Vernacular Springcloud | Chapter II: Service Registration and Discovery (Eureka)-Upper

Source: Internet
Author: User

Objective

Starting from this section, formally enter SpringCloud the basic tutorial. From the first chapter "What is Springcloud" we can know that a microservices framework covers a lot of things, and how to manage these services or API interfaces, it is very important. So in this chapter, we mainly introduce the SpringCloud Eureka implementation of service registration and discovery.

    • Service governance
    • Eureka Practice
      • Eureka Brief Introduction
      • Create a Eureka service side
      • Create Eureka Client
      • Eureka Self-protection mode
    • Resources
    • Summarize
    • At last
    • Cliché
Service governance

Service governance is the most core and basic module in MicroServices architecture. It is mainly used for automating the registration and discovery of each micro-service instance.

Here's a classic picture:

As you know, as services become more and more cluttered, calls between services become more complex and more difficult to manage. And when a service changes, or because of stress performance problems, more than a few services deployed, how to make the service consumers aware of the changes, it is very important. Otherwise, there will be a call service is actually offline, but the caller does not know the exception condition.

It is important to have a service component to unify governance at this time. Simply put, a service governance component should have the following features:

Service Registration Form

The core of the service governance component, which is used to record information about each microservices, such as the name of a microservices, IP, ports, and so on. The Service Registration component provides the query API and the management API, which is used by the query API to query the available microservices instances, and the management API is used for service registration and logoff.

Service Registration and Discovery

    • Service registration refers to the process by which a microservices registers its own information with the service governance component at startup.
    • Service discovery refers to the mechanism of querying the list of available microservices and their network addresses.

Service check

The service governance component uses a mechanism to periodically detect registered services, whether they are online, or if they cannot connect, and if they are unable to access them, they are removed from the service registry for offline operation.

Eureka Practice Eureka Simple Introduction

Eurekais the Netflix Open Source Service discovery component, which itself is a REST service based. It contains Server and Client two parts. Spring Cloudintegrate it in sub-projects Spring Cloud Netflix to enable the registration and discovery of microservices.

Off topic: Interested classmates can search to see this online video rental provider:Netflix. Most of the family barrels in contact with the company's open source, old!

Netflix official GitHub address below: Https://github.com/Netflix

Eureka Service Side

Also known as a registry, to provide registration and discovery of services. Supports highly available configurations that provide good service instance availability with strong consistency and can handle a variety of different failure scenarios.

Eureka Client

The main processing service registration and discovery. The client service is embedded in the client's application code with annotations and parameter configuration, registering the service itself with the registry when the application starts, and periodically sending a heartbeat to update its service lease. At the same time, it can query the current registered service information from the server and cache them locally and periodically refresh the service state.

Simply look at the Eureka overall architecture:

From this diagram, it can be seen that Eureka there are three components:

    • Service Provider: Provider of exposed services.
    • Service Consumer: Calls the services consumer of the remote service.
    • EureKa Server: Service registration center and Service Discovery Center

And we use the Eureka main is to achieve 服务治理功能 , through our general understanding of its governance system:

Simply put, the client obtains the address information of the service-side service through the registry, and then calls the service according to the address, while the Registry maintains the status of each service, such as sending the heartbeat verification health state, judging whether it is online, and recording its service address for querying.

Before beginning to explain the example, the next to the version can be unified management, this series of tutorials created a parent pom file, the use Maven of the dependencyManagement module version is unified management. If the subsequent upgrade version, the normal update of this parent POM version can be.

Create a Eureka service side

Creating a Eureka server is simple, we just need a few simple steps to complete.

Create a spring-cloud-eureka-server project that is named SpringBoot .

0. Join Pom dependency.

    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>    </dependency>

Note here, unlike the E version, the E version is introduced spring-cloud-starter-eureka-server :.

1. Add configuration file configuration.

spring.application.name=eureka-service# 修改端口server.port=1000# 实例的主机名称eureka.instance.hostname=127.0.0.1## 不要向注册中心注册自己eureka.client.register-with-eureka=false## 表示不去检索其他的服务,因为服务注册中心本身的职责就是维护服务实例,它也不需要去检索其他服务eureka.client.fetch-registry=false# 指定服务注册中心地址 这里直接指向了本服务eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/

Friendly tip: Because eureka.client.service-url in the configuration class org.springframework.cloud.netflix.eureka.EurekaClientConfigBean is a map object, so, the use of the IDE's hint function is not to appear, but also pay attention to map the value of the object, the case should be consistent, and other objects are not the same, this should be noted.

So from the source can be seen, the default is not written, is registered to: DEFAULT_URL , the default is http://localhost:8761/eureka .

2. Start the class and add the annotation @enableeurekaserver.

/** * Eureka服务端 * @author oKong * */@SpringBootApplication@EnableEurekaServer@Slf4jpublic class EureakServiceApplication {        public static void main(String[] args) throws Exception {        SpringApplication.run(EureakServiceApplication.class, args);        log.info("spring-cloud-eureka-service启动!");    }}

3. Launch the app, visit: http://127.0.0.1:1000/,

So far a stand-alone Eureka service has been built. is not very simple, basically just a few lines of code. As can be seen, there is no service registration up, so the application list is empty. Next, create a client to register at the same time under this registry.

Create Eureka Client

EurekaThe client, in fact, is the provider of services, the application of external services.

Create a spring-cloud-eureka-client project.

0. Join Pom Dependency

    <!-- 客户端依赖 -->    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>    </dependency>    <!-- 引入web,提供一个简单的api接口 -->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-web</artifactId>    </dependency>    

1. Configure the file to add the registration center configuration.

spring.application.name=eureka-clientserver.port=2000# 注册中心地址eureka.client.service-url.defaultZone=http://127.0.0.1:1000/eureka# 启用ip配置 这样在注册中心列表中看见的是以ip+端口呈现的eureka.instance.prefer-ip-address=true# 实例名称  最后呈现地址:ip:2000eureka.instance.instance-id=${spring.cloud.client.ip-address}:${server.port}

Friendly tip : Here is a hole, variable spring.cloud.client.ipAaddress in the F version should be written spring.cloud.client.ip-address . The specific reason is that the field name has been modified.

org.springframework.cloud.client.HostInfoEnvironmentPostProcessorClass:

2. Start class Join note enablediscoveryclient.

/** * 服务提供者示例-eureka客户端 * @author oKong * */@SpringBootApplication//注意这里也可使用@EnableEurekaClient//但由于springcloud是灵活的,注册中心支持eureka、consul、zookeeper等//若写了具体的注册中心注解,则当替换成其他注册中心时,又需要替换成对应的注解了。//所以 直接使用@EnableDiscoveryClient 启动发现。//这样在替换注册中心时,只需要替换相关依赖即可。@EnableDiscoveryClient@Slf4jpublic class EurekaClientApplication {    public static void main(String[] args) throws Exception {        SpringApplication.run(EurekaClientApplication.class, args);        log.info("spring-cloud-eureka-client启动!");    }}

Note: @enableeurekaclient annotations can also be used here, but they are not generally used, and are automatically discovered using @enablediscoveryclient directly. Because of SpringCloud its own support Eureka , and Consul zookeeper so on to implement the registry function, if you write dead a registry of relevant annotations, and then replace, you also need to modify the annotation class.

3. Write a simple API interface.

/** * 简单api示例 * @author oKong * */@RestControllerpublic class DemoController {    @GetMapping("/")    public String index() {        return "spring-cloud-eureka-client!";    }}

4. Launch the app and visit again: http://127.0.0.1:1000/, you can see that the service is registered.

Eureka Self-protection mode

During the development phase, the following text is often present:

By default, if the Eureka Server heartbeat of a microservices instance is not received within a certain amount of time, Eureka Server the instance is logged off (the default is 90 seconds). However, when a network partition failure occurs, the MicroServices and Eureka Server do not communicate properly, which can become very dangerous, because the microservices itself is healthy, at this time should not be unregistered this micro-service.

Eureka ServerBy "Self-protection mode" to solve this problem, when the Eureka Server node in a short period of time to lose too many clients (possibly a network partition failure), then this node will enter the self-protection mode. Once in this mode, the Eureka Server information in the service registry is protected and data in the service registry is no longer deleted (that is, no microservices are unregistered). When a network failure is restored, the Eureka Server node automatically exits self-protected mode.

Self-protection mode is a kind of security protection measure for network anomaly. Use self-protection mode to make the Eureka cluster more robust and stable.

The development phase can be configured by: eureka.server.enable-self-preservation=false Turn off self-protection mode.

At the production stage, it should be configured with the default values.

As to the specific configuration parameters, can be viewed on the official website: http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html#_ Appendix_compendium_of_configuration_properties

Or simply view EurekaClientConfigBean and EurekaInstanceConfigBean class-related default configurations:

As for the Chinese description of the field, you can view the website: micro-Service Architecture: Eureka parameter Configuration items in detail, inside the detailed description.

"You say, English is not good even the field what meaning do not know, how embarrassed, learn English very important, (┬_┬)"

Resources
    1. Http://cloud.spring.io/spring-cloud-static/Finchley.RELEASE/single/spring-cloud.html#spring-cloud-eureka-server

    2. 76222517

    3. Https://www.areatao.com/article/5b45718d7ab07c574d5888d0

Summarize

This article explains how to build a Eureka registry, and use the Eureka Client registration service to the registration center. Configuration and use are relatively simple, the main thing is to understand Eureka what we have done, and provide what service governance strategy. Currently we are building a stand-alone version of the registration center, would like to continue to write Eureka the high availability and its access to security. But today is a business trip, evening back to the hotel late. After writing the last chapter of this chapter, I feel sleepy and divided into the upper and lower chapters. Understanding, Understanding, (┬_┬)

At last

At present, the Internet on the big guys have to share a SpringCloud series of tutorials, content may be similar, hope to forgive. The original is not easy, the code word is not easy, but also hope that everyone support. If there are errors in the text, also hope to put forward, thank you.

Cliché
    • Personal QQ:499452441
    • Public Number:lqdevOps

Personal blog: http://blog.lqdev.cn

Source code example: https://github.com/xie19900123/spring-cloud-learning

Original address: http://blog.lqdev.cn/2018/09/06/SpringCloud/chapter-two/

Vernacular Springcloud | Chapter II: Service Registration and Discovery (Eureka)-Upper

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.