Vernacular Springcloud | Chapter III: Service Registration and Discovery (Eureka)-Next

Source: Internet
Author: User
Tags zookeeper
Objective

The previous section explains the knowledge points and simple examples of service registration and discovery in stand-alone mode. In the actual production or in a distributed environment of this microservices architecture, it is necessary to consider the high availability of each component in the event of a failure. In fact, high availability, my simple vulgar understanding is that through the redundancy of the system is highly available, or a cluster deployment, to ensure that a service is not available, will be automatically transferred to the available services. For today's chapters, let's talk about Eureka the high availability.

    • A little knowledge
      • Cap principle
      • The difference between Eureka and zookeeper
    • Eurkea High Availability Introduction and examples
      • Eureka High-availability
      • Eureka Service-Side High availability
      • Eureka Client registration to the cluster
      • Highly Available tests
      • A Little doubt
      • A brief discussion on cluster configuration
    • Eureka Registration Center Access Certification
    • Resources
    • Summarize
    • At last
    • Cliché
A little knowledge

Before we talk, let's start by talking about the Dubbo difference between what you hear and what you can do with it Zookeeper Eureka .

Cap principle

According to the definition of Baidu Encyclopedia, Cap theorem is also called the cap principle, refers to in a distributed system, consistency (consistency), availability (availability), Partition tolerance (partition fault tolerance), Can only be at the same time three of the characteristics of two, three can not be combined.

In the field of distribution, we should CAP not be unfamiliar with the theory (understand but also did not understand @@facesymbol@@‖∣).

The following excerpt to Baidu Encyclopedia :

Consistency (C): All data in the distributed system is backed up, at the same time whether the same value. (equivalent to all nodes accessing the same copy of the latest data)

Availability (A): After a partial node failure in the cluster, the cluster is still able to respond to client read and write requests. (High availability for data updates)

Partition fault tolerance (P): As a practical result, partitions are equivalent to the time-limit requirements for communication. If the system cannot achieve data consistency within the time frame, it means that the partition has occurred and that a choice must be made between C and a for the current operation.

As for why can not be satisfied at the same time, the above partition fault tolerance also has a simple explanation, in general, partition fault tolerance can not be avoided, so it is always possible to think that CAP the P consistency and availability of why cannot be met at the same time, Simply put: there may be communication failure situation, that is: partition fault tolerance , as far as more detailed concrete, we can see the big guy Ruan Yi Feng 's article: The meaning of the CAP theorem. Here is not elaborated, not very understanding ~

The difference between Eureka and zookeeper

For Eureka, it is satisfied AP , and zookeeper is satisfied CP .

The Eureka is satisfying AP :

    • Priority to ensure availability
    • Each node is equal, several nodes will not affect the normal node work, the remaining nodes can still provide registration and query services
    • If a connection fails when it is registered to a Eureka, it will automatically switch to the other node, as long as a Eureka is still in the service to ensure that the registration services are available (guaranteed availability), except that the information found may not be up-to-date (strong consistency is not guaranteed)

The zookeeper is satisfying AP :

    • Consistent data results for zookeeper access requests at any time, and system-to-network segmentation with fault tolerance
    • Availability of each service request is not guaranteed
    • When the master node loses contact with other nodes because of a network failure, the remaining nodes re-leader the election
    • The election leader was too long, at 120s, and the entire ZK cluster was unavailable during the election period, which led to the paralysis of registration services during the election

My simple understanding: Because Zookeeper of the loader election strategy, so that it can guarantee the consistency of data. And Eureka , there is no electoral strategy, the services are independent operation , at least at a certain time, the data between the services are inconsistent, and in terms of availability, Zookeeper but also because of the election strategy, during the election period is, the whole zookeeper is not available, will cause short ( Look at the election time) service is not available. In Eureka other words, the service is run independently, so no other service is unavailable because one of the services is not available. The feeling is a bit around, in short, is to Zookeeper ensure the consistency of data through the election strategy , but the lack of availability, Eureka because the service runs independently , through the heartbeat and other communication strategies for data synchronization, There is data inconsistency, but the availability of the service is guaranteed .

So, in summary, the usability principle is more important than data consistency as a service registry , and the previous section has said that, due to the Eureka self-protection model , The information in the service registry can be protected from being rejected, so Eureka it is good to be able to cope with a network failure that causes the node to lose contact .

Eurkea High Availability Introduction and example Eureka High availability

In the official website, the Eureka high-availability section is described as follows:

So it can be learned that Eureka Server multiple instances can be run to build a cluster, solve a single point of problem, using peer to peer Eureka Server communication . This is a centralized architecture, no master/slave distinction, and each peer is equal to each other. In this architecture, nodes increase availability by registering with each other, and each node needs to add one or more valid serviceurl to point to the other nodes. Each node can be treated as a copy of another node.

If an outage occurs, Eureka Server Eureka Client the request is automatically switched to the new node, and once the Eureka Server outage server is restored, it is Eureka again incorporated into the server cluster management. When a node begins to accept a client request, all operations are performed replicateToPeer(节点间复制) and the request is replicated to Eureka Server all other nodes currently known.

So, in simple terms, Eureka Server the high availability, in fact, is to register themselves as a service to other service registries, so that you can form a set of mutual registered service registries, in order to achieve the synchronization of the service list, to achieve a highly available effect.

In addition, it is mentioned in the official website document, Zones Regions Region and Zone (or availability Zone) is the concept of AWS . In a non-AWS environment, we can first simply understand region as Eureka Cluster, zone understanding into a room. Can be understood as a Eureka cluster is deployed in the Zone1 room and the Zone2 room.

Other relevant knowledge of these concepts, but also in-depth understanding, we are interested, you can search the next bar.

Example, let's look at the architecture diagram of Eureka in cluster mode.

    1. Service provider will do operations such as register (service registration), Renew (service renewal), Cancel (service downline) to Eureka Server.
    2. Synchronization of registration services between Eureka servers ensures consistent state
    3. Service consumer will get a list of registered services to Eureka Server and consume services

Specific analysis of the principle, you can look at this earlier article: nobodyiam.com/2016/06/25/dive-into-eureka/, although it is relatively early article, but write a more detailed, you can see.

Next, take the official website document demo, the example below.

Eureka Service-Side High availability

With point-to-point configuration, registries achieve highly available configurations by registering with each other. The following builds a two-node cluster pattern.

Modify the spring-cloud-eureka-server project.

0. Create a application-ha.properties configuration file and modify the file at the same time application.properties .

application-ha.properties

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

application.properties

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

1. Because it is in the same simulation, the first modification of the hosts file, when the browser requests an address, the first will be selected from this file corresponding IP address, not found when the request CDs domain name resolution server for resolution

C:\Windows\System32\drivers\etc\hostsFile:

127.0.0.1 myPeer1127.0.0.1 myPeer2

Tips: If prompted without modification permissions, can be modified according to the following URL: How to edit the Hosts file cannot be saved

2. Launch the application, we start the two directly here, you can change the spring.profiles.active value to start the application of different environments, or use -jar xx.jar --spring.profiles.active=xx to start.

Visit: http://myPeer1:1000

Visit: http://myPeer2:1001

Off-topic: the first application launched, the background will be error Connection refused: connect , and so on after the second application started, it is normal ~

Eureka Client registration to the cluster

The client only needs to modify the value of the configuration file eureka.client.service-url.defaultZone .

Modify spring-cloud-eureka-client Project

0. Modify the configuration fileapplication.properties

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

Of course, can also be registered only to a node, other nodes will also have this list of services, generally recommended cluster configuration, that is, multi-registration center configuration. To avoid a single point of failure, Eureka search the registry, according to the Defaultzone list, find a usable, and then will not continue to the next registry address to pull the list of services, if one of the registration center is hung, this time the client will continue to the second registry to pull the service list.

After starting, you can see eureka-client the registration up.

Now that we've stopped an app, we can see that there's already information in the list of unavailable services.

Highly Available tests

To verify that high availability is successful, create a spring-cloud-eureka-server-ha-test project that serves as a service that the consumer uses RestTemplate+ribbon to make spring-cloud-eureka-client the call.

Create a spring-cloud-eureka-server-ha-test Project
0. Introduction of POM Dependency

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

1. configuration file, configuring the registry address

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

2. Start the class, configure RestTemplate The Bean class, and join the @loadbalanced annotation to implement the service invocation.

@SpringCloudApplication@EnableDiscoveryClient@Slf4jpublic class EurekaServiceHaApplication {        public static void main(String[] args) throws Exception {        SpringApplication.run(EurekaServiceHaApplication.class, args);        log.info("spring-cloud-eureka-server-ha-test启动!");    }        //加入负载均衡能力    //同时可根据applicationName 来访问服务    //如http://EUREKA-CLIENT/add    @Bean    @LoadBalanced    public RestTemplate restTemplate() {        return new RestTemplate();    }}

3. Write a control class and simply invoke the EUREKA-CLIENT service method.

/** * 调用简单示例 * @author oKong * */@RestControllerpublic class DemoController {    @Autowired    private RestTemplate testTemplate;        @GetMapping("/")    public String index() {        //访问服务提供者        return testTemplate.getForObject("http://EUREKA-CLIENT/", String.class);    }}

4. Launch the App class to access the registry and http://127.0.0.1:8888.

The visible output spring-cloud-eureka-client! indicates that the call was successful. From the console you can also see the service address that was pulled from the registry EUREKA-CLIENT :

This time, you can try to stop one or even all of them, and Eureka Server then continue to access, you can see the service can be called, but know that at this time the caller is likely to be based on the local cache list directly to obtain the address, rather than from the registration service center, waiting for the next heartbeat mechanism time to, To pull up the latest list of services.

About RestTemplate and the Ribbon relevant knowledge points, will be elaborated in the next section, here is not open.

A Little doubt

The first time crossing Web document to demo, still want to set the port number is not OK, why also need to specify eureka.instance.hostname , how much trouble? Try using IP or not configuring it.

    • eureka.instance.hostnamewhen modified to localhost or 127.0.0.1 ,

You can see that DS Replicas there is nothing in the, and the description is empty, and the service is not replicable registered-replicas available-replicas .

Client Configuration eureka.client.service-url.defaultZone .

eureka.client.service-url.defaultZone=http://127.0.0.1:1001/eureka,http://127.0.0.1:1000/eureka

Will find that 1001 there is a registration on the service, the 1000 service has no service information. (client registration is a sequential priority for registering and getting a list of services)

1001 Service:

1000 Service:

This indicates that the cluster mode is not in effect and there is no Replication Service list between the registries.

    • Modify the configuration file, one modified 127.0.0.1 to another, localhost or the actual intranet IP address

Description under:
1001 corresponds hostname to: 127.0.0.1
1000 corresponds hostname to: 192.168.81.1

1001 Service:

1000 Service:

Will find that the cluster mode is successful.
Then we start the client.

1000 Service:

1001 Service:

Can be seen, and the above settings myPeer1 and myPeer2 effects are the same, have been copied.

A brief discussion on cluster configuration

From the above can be roughly learned that Eureka each other registration requirements for each Eureka server instance of the eureka.instance.hostname different, if the same, it will be Eureka marked unavailable-replicas (like the local set to 127.0.0.1, simply do not show, specifically unknown. @@facesymbol@@‖∣), the previous synchronization fails. For the configuration of the client defaultZone , it is preferred to start from the first registration and pull the service, the successful unicom will not continue to find the next registration service.

Sum up:

    • If you are deploying multiple services for a single server, Eureka server set up each service
      , and hostname to be set to eureka.instance.prefer-ip-address false , do not register with an IP address.
    • When multiple server deployments are set to the native hostname IP address, variables can be used to spring.cloud.client.ip-address assign values. Also set eureka.instance.prefer-ip-address to true . In this case, the client uses the IP connection is convenient, or to configure the host a bit of a pit.
    • It is recommended for the client to defaultZone configure multiple registry addresses . Even if the cluster mode is not valid, at least one of them can not be used, but also to the other registration center AH.

At the end of the final, the search for an article, but also the general meaning, you can click to see: Build a highly available Eureka Registration Center

Its source address: github.com/wangfei0904306/eureka-ha

The above may understand the deviation, but also want to know the students can not hesitate to enlighten, thank you!

Eureka Registration Center Access Certification

By default, access to the registry page is anonymous and does not require some authentication. In the production, for security, you can join the identity authentication function.

Adding certifications is simple, and official website documentation also shows:

0. Join Pom Dependency:

    <!-- 开启认证 -->    <dependency>        <groupId>org.springframework.boot</groupId>        <artifactId>spring-boot-starter-security</artifactId>    </dependency>

1. Modify the configuration file, set the user name and password and the cluster status, when registering to another service center, add the user name and password:

# 设置帐号密码# 若不设置 默认帐号是user,密码随机,启动时会打印在控制台上spring.security.user.name=oKongspring.security.user.password=123456# 加入用户名和密码eureka.client.service-url.defaultZone=http://oKong:123456@127.0.0.1:1001/eureka

Friendly tip: When you do not set the name and password, the default user is username, the password is random and will be printed on the console at startup:

2. Modify the startup class, according to the official website prompt, close /eureka/** the CSRF token.

/** * 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启动!");    }        /**     * 忽略此路径下的CSRF令牌     * @author oKong     *     */    @EnableWebSecurity    static class WebSecurityConfig extends WebSecurityConfigurerAdapter {        @Override        protected void configure(HttpSecurity http) throws Exception {            http.csrf().ignoringAntMatchers("/eureka/**");            super.configure(http);        }    }    }

3. Launch the app. Visit again: http:127.0.0.1:1000, you need to enter the user name and password.

4. The client is similar, modify the defaultZone user name and password can be added:

eureka.client.service-url.defaultZone=http://oKong:123456@127.0.0.1:1001/eureka,http://oKong:123456@127.0.0.1:1000/eureka
Resources
    1. Cloud.spring.io/spring-cloud-static/finchley.sr1/single/spring-cloud.html#spring-cloud-eureka-server

    2. nobodyiam.com/2016/06/25/dive-into-eureka/

    3. http://tech.lede.com/2017/03/15/rd/server/SpringCloud1/

    4. 79056083

Summarize

This section is mainly Eureka about the high availability of services under the simple introduction. For some of the best practices in cluster mode is still to be discussed, but also hope that we can talk about the solution from a! As for some other features, such as 元数据 configuration, this is not explained here, not much. At the same time, this chapter uses a RestTemplate+ribbon simple service invocation, not open, the next chapter is to begin to explain the 服务消费者 relevant knowledge points, should also be divided into two chapters to describe, because involved Ribbon and Feign relevant knowledge points. I always feel that the use is very simple, only to understand the principle of the inside and so on, this is the follow bar, deepen the impression! It can also be used more smoothly.

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: github.com/xie19900123/spring-cloud-learning

Original Address:/HTTP

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.