Eureka principle and the principle of CAP

1 Eureka

1.1 What is the Eureka registry

EurekaIs Netflixthe development of service discovery component itself is based on a RESTservice.
Spring CloudIt will be integrated in its children spring-cloud-netflixin order to achieve Spring Cloudservices 注册于发现, while also providing 负载均衡, 故障转移and other capabilities.

1.2 Eureka registry three roles

1.2.1 Eureka Server

By Register、 Get、 Renewproviding services such as registration and discovery interfaces.

1.2.2 Application Service (Service Provider)

服务提供方: The self-service instance is registered Eureka Serverin

1.2.3 Application Client (Service Consumer)

服务调用方: By Eureka Serveracquiring the list of services, consumer services

1.3 Schematic

Here Insert Picture Description
Register(服务注册): Their own IPregistration and to the port Eureka.
Renew(服务续约): Sending a heartbeat packet every 30transmission time in seconds. Tell Eurekahe was still alive.
Cancel(服务下线): When providerwill the closing Eureka, to remove yourself from the list of services to send messages. To prevent consumercalls to non-existent service.
Get Registry(获取服务注册列表): Get a list of other services.
Replicate(集群中数据同步): eurekaData cluster replication and synchronization.
Make Remote Call(远程调用): Complete remote service invocation.

2 CAP

2.1 What is the principle of CAP

CAPPrinciple, also known CAPtheorem, refers in a 分布式系统medium, Consistency(consistency), Availability(availability), Partition tolerance(partitions fault tolerance), the three can not have both.

Principles of classification Detailed
C
data consistency ( Consistency)
Also called system data atom is still in a consistent state after performing an operation. In a distributed system, the update operation after the successful implementation of all users should read the latest value of such a system is considered to be 强一致性in. Equal access to the same copy of the latest copy of the data to all nodes
A
Service Availability ( Availablity)
Each operation always returns results within a certain time, here be noted that 一定时间内and 返回结果. Refers to a certain period of time, returns results within a tolerable range, the result may be a success or failure
P
partition fault tolerance ( Partition-torlerance)
In the case of network partitioning, separated by a node can still provide services outside normal (distributed clusters, distributed data is stored on a different server, no matter what the case, the server can normally be accessed)

2.2 How to give up

定律: Any distributed system only at the same time满足二点,没法三者兼顾

The other three selection analysis
CA, 放弃 P If you want to avoid partition fault tolerance problem, an approach is all the data (and related transactions) are placed on a machine. While it is not 100% guaranteed system can not go wrong, it will not be met by a single partition the negative effects. Of course, the expansion of the serious implications of this system will be selected
CP, 放弃 A Relative to abandon the "Partition fault tolerance", the opposite is to give up its availability. In the event of a fault-tolerant partition fails, then the affected services need to wait for some time, so the system can not provide service outside in the waiting time
AP, 放弃 C Mentioned here give up consistency, data consistency is not completely give up, but giving up the strong consistency of the data, while final data consistency. To online shopping as an example, only a lower inventory of goods, if also received two orders, the order will be informed later of goods sold out

2.3 eureka difference with the zookeeper

Comparison items Zookeeper Eureka
CAP CP Of
Dubbo integration It has supported -
Spring Cloud Integration It has supported It has supported
kv Service stand by - ZK supports data storage, eureka not supported
Using an interface (multi-language) Providing clients http multilingual ZK cross-language support is relatively weak
watch support stand by stand by What is Watch support? That is, a single customer service side of the monitor changes. zk to achieve eureka be achieved by way of polling by subscribing to monitor
Cluster Monitoring - metrics metrics, operation and maintenance can collect these metrics and alarm information to achieve the purpose of monitoring

3 eureka elegant stop taking

3.1 Eureka self-protection

3.1.1 self-protection conditions

In general, micro service Eurekaafter registration, it will be every 30second heartbeat packets are sent, Eurekato determine whether the health service by heart, and it will periodically delete more than 90seconds, did not send a heartbeat service.

3.1.2 Eureka Server can not receive heartbeat micro services

  • Micro-service their own reasons
  • With micro-services Eurekanetwork failure between, usually (own fault shut micro-services) can only lead to failure of individual services, general large-scale failure does not occur, and (network failure) usually results Eureka Servercan not be closed in a short time to a large number of heartbeat.
    Taking into account this distinction, Eurekaset up a 阀值, when it is judged hang up the number of services exceeds the threshold, Eureka Serverthink to a large extent there has been a network failure, the heart will not delete the expired service.

3.1.3 eureka threshold

  • 15It is lower than within minutes 85%;
  • Eureka ServerDuring operation, the statistics of heart failure in the proportion 15is below within minutes 85%of this algorithm is called Eureka Serverself-protection mode

3.2 Why do we need to protect themselves eureka

  • Because while retaining 好数据and 坏数据better than losing any data to be better, when the network fault recovery, the Eurekanode will exit 自我保护模式.
  • EurekaAs well as client-side caching function (that is, micro-service caching function). Even if Eurekathe cluster nodes are down all fail, micro services Providerand Consumercan communicate properly.
  • Micro-service 负载均衡policies are automatically removed micro-services node death

3.3 Close self-protection

Modify Eureka Serverthe configuration file

#关闭自我保护:true 为开启自我保护, false 为关闭自我保护
eureka.server.enableSelfPreservation=false
#清理间隔(从服务列表删除无用服务的时间间隔,单位:毫秒, 默认是 60*1000)
eureka.server.eviction.interval-timer-in-ms=60000

3.4 elegance stop taking

surroundings:springboot:2.1.3 springcloud:Greenwich.SR5

3.4.1 does not need to protect themselves in the closed configuration in Eureka Server

3.4.2 adding the coordinates of dependent actator

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

3.4.3 modify the properties file

###### 优雅停服######
##启用 shutdown
management.endpoint.shutdown.enabled=true
# 暴露所有端点
management.endpoints.web.exposure.include=*
#禁用密码验证
management.endpoints.shutdown.sensitive=false

3.4.4 Service URL request sent Close

postrequest

public static String doPost(String url,Map<String,String> param)  {
		//创建HTTPClient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		String resultString = "";
		CloseableHttpResponse response = null;
		try{
			//创建httpget请求
			HttpPost httpPost = new HttpPost(url);
			if(MapUtils.isNotEmpty(param)) {
				List<NameValuePair> paramList= new ArrayList<>();
				param.forEach((a,b)->paramList.add(new BasicNameValuePair(a,b)));
				//模拟表单
				UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramList,"utf-8");
				//UrlEncodedFormEntity 来设置 body,消息体内容类似于“KEY1=VALUE1&KEY2=VALUE2&...
				httpPost.setEntity(formEntity);
			}
			//执行请求
			response = httpClient.execute(httpPost);
			if(response.getStatusLine().getStatusCode()==200) {
				System.out.println("========成功========");
				resultString = EntityUtils.toString(response.getEntity(),"utf-8");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(response!=null)response.close();
				httpClient.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return resultString;
	}

mainSend method

public static void main(String[] args) throws Exception {
		String url ="http://127.0.0.1:9080/actuator/shutdown";
		//该 url 必须要使用 dopost 方式来发送
		HttpClientUtil.doPost(url,null);
	}

In mainthe transmission method, you can see yourself in the local start of the service shut down, can also be viewed in the service registry page

4 eureka safety certification

4.1 Adding security package in Eureka Server

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

4.2 modify Eureka Server configuration file

#开启 http basic 的安全认证 没有用 需要通过下面方法来关闭或开启
#spring.security.basic.enabled=true
spring.security.user.name=user
spring.security.user.password=123456
 # 修改访问集群节点的 url
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka2:8761/eureka/

4.3 modified micro-service configuration file to add access to the registry of the user name and password

spring.application.name=eureka-provider
server.port=9090
#设置服务注册中心地址, 指向另一个注册中心
eureka.client.serviceUrl.defaultZone=http://user:123456@eureka1:8761/eureka/,http://user:123456@eureka2:8761/eureka/
#启用 shutdown
management.endpoints.shutdown.enabled=true
#禁用密码验证
management.endpoints.shutdown.sensitive=false

4.4 Close csrf certification

Spring Cloud 2.0The above securityis enabled by default csrfinspection, to the eurekaServerside configuration securityof csrforder to testfalse

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable(); //关闭csrf
        //开启认证  若注释掉,就关闭认证了
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); 
    }
}
Published 334 original articles · won praise 186 · views 310 000 +

Guess you like

Origin blog.csdn.net/u012060033/article/details/104362583