table of Contents
Realize highly available eureka
The difference between zookeeper and eureka
About eureka interview questions and answers
Summary
Whether we are doing distributed development or microservice development, we need to contact a component, that is, the service governance center. There must be a component to provide you with the function of discovering services. The registry can be performed by frameworks such as zookeeper, reids, eureka, etc. Because our series focuses on springcloud, this article mainly introduces eureka components, and the differences between these types of registry will be discussed later.
Introduction to eureka
Spring cloud eureka is a secondary encapsulation based on netflix eureka. It is mainly responsible for implementing the service governance function in the microservice architecture. Springcloud eureka is based on the rest communication method on the http protocol and provides corresponding client components, which can be very convenient Service governance. Service governance must have a registry. In addition to using eureka as the registry, zookeeper can also be used as the registry. Ali's open source dubbo framework can support zookeeper as the registry. Those who have used dubbo know that dubbo provides zookeeper in addition to zookeeper. As a registry, it can also support frameworks such as redis as a registry. People who are new to microservices or distributed may not know what a service registry is. I will briefly describe it for you. You can look at this picture.
The above figure describes the main functions of the registry. Producers can provide services and request services from the registry as consumers. If you don’t know the registration center very well, then look at the picture below:
eureka actual combat
Development tools: IDEA, jdk version: 1.8 maven 3.5.4
Service registry development
1. Create an empty project and name it springcloud-blog
After opening the project, add a new module
2. Add a new module
Keep clicking next to complete the project creation
3. Add dependencies. In order to ensure the consistency of subsequent operations, it is recommended to copy the following dependencies to the pom file
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
4. Turn on eureka service governance function
添加@EnableEurekaServe注解开启
@SpringBootApplication
//开启服务治理功能
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}
5. Integrated security framework to realize eureka security authentication
Add the following configuration class
@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic();
}
}
6. Edit the configuration file
The springboot project created by idea is used by default, and the generated configuration file is application.properties. It is recommended to use the yml format, which is more concise and clear, directly modify the suffix application.yml
Paste the following content
spring:
application:
# 服务名
name: eureka-server
# security安全认证配置
security:
user:
name: yangle
password: 123
server:
port: 8761
eureka:
client:
# 该应用为注册中心,不需要向注册中心注册自己
register-with-eureka: false
# 关闭检索服务的功能,只需要维护服务
fetch-registry: false
7. Run the main method to start eureka
8. An error will be reported in the test after startup
We delete this line, and then re-import the test package
9. After the project is started, visit http://localhost:8761/ and enter the username and password yangle 123
Seeing the above page, it means that eureka has started successfully, and then we develop service producers
Service producer development
1. Create a springboot project
After the project is built, there is a prompt in the lower right corner to click show, and then you can start the springboot project easily.
2. Copy dependencies
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR2</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
3. Turn on the service discovery function, edit the application file, and add
@EnableDiscoveryClient
@SpringBootApplication
//开启服务发现功能
@EnableDiscoveryClient
public class EurekaClientProducterApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientProducterApplication.class, args);
}
}
4. As before, change the suffix of the configuration file to yml, and copy the following
spring:
application:
name: eureka-client-order-service
server:
port: 8081
eureka:
client:
serviceUrl:
# 指定注册中心
defaultZone: http://yangle:123@localhost:8761/eureka
instance:
#可选
preferIpAddress: true
#实例ID支持自定义,可选
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
5. Add an order to get service
@RestController
public class OrderService {
@RequestMapping("getOrder")
public String getOrder(){
return "{code:0,data:{}}";
}
}
6. Let's start this project and see if it starts normally http://localhost:8081/getOrder
We reopen http://localhost:8761/ and we will see that the producer has been registered in the registry
Service consumer development
, Just like the producer, just change the project name to eureka-client-consumer
1. Modify the yml file
spring:
application:
name: eureka-client-order-consumer-service
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://yangle:123@localhost:8761/eureka
instance:
preferIpAddress: true
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
2. Inject restTemplate into the container. SpringRestTemplate is a client provided by Spring for accessing Rest services. RestTemplate provides a variety of convenient methods to access remote Http services, which can greatly improve the efficiency of client writing, so many clients such as Android Or third-party service providers use RestTemplate to request restful services
@SpringBootApplication
public class EurekaClientConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientConsumerApplication.class, args);
}
@Bean(name = "restTemplate")
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
3. Add an interface to call the service provided by the producer
@RestController
public class OrderConsumerService {
@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;
@RequestMapping("getOrder")
public String getOrder(){
//IP替换为自己的本地IP
return restTemplate.getForObject("http://IP:8081/getOrder",String.class);
}
}
The resttemplate is used here to call this service. Although this calling method is simple, it has a drawback that when our service is deployed in a cluster, it is difficult to perform load balancing quickly, because it specifies which node to call. Service, of course, this piece of springcloud also thought of us
4. Use the annotation @LoadBalanced to call through the service name and modify the configuration content
@SpringBootApplication
public class EurekaClientConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientConsumerApplication.class, args);
}
@Bean(name = "restTemplate")
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
@Bean(name = "restTemplate2")
@LoadBalanced
public RestTemplate getRestTemplate2() {
return new RestTemplate();
}
}
5. Add resttemplate that implements loadbalence function
@RestController
public class OrderConsumerService {
@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;
@Autowired
@Qualifier("restTemplate2")
private RestTemplate restTemplate2;
@RequestMapping("getOrder")
public String getOrder(){
return restTemplate.getForObject("http://192.168.31.168:8081/getOrder",String.class);
}
// 实现负载均衡的服务,不需要指定节点,只需要指定使用的服务名称
@RequestMapping("getOrderForLoadBalence")
public String getOrderForLoadBalence(){
return restTemplate2.getForObject("http://eureka-client-order-service/getOrder",String.class);
}
}
6. After starting the project, visit the new interface again to see if the visit is successful
7. View eureka face to see. I saw that consumers also registered
Realize highly available eureka
Implementation principle: By adding a new registration center, and then let them register with each other to achieve high availability
Copy the eureka-server project and rename it to eureka-server-slave
Modify the configuration file of eureka-server-slave
spring:
application:
name: eureka-server
security:
user:
name: yangle
password: 123
server:
port: 8762
eureka:
client:
serviceUrl:
defaultZone: http://yangle:123@localhost:8761/eureka
Modify the configuration file of eureka-server
spring:
application:
name: eureka-server
security:
user:
name: yangle
password: 123
server:
port: 8761
eureka:
client:
serviceUrl:
defaultZone: http://yangle:123@localhost:8762/eureka
Modify the configuration files of producter and consumer
生产者
spring:
application:
name: eureka-client-order-service
server:
port: 8081
eureka:
client:
serviceUrl:
defaultZone: http://yangle:123@localhost:8761/eureka,http://yangle:123@localhost:8762/eureka
instance:
preferIpAddress: true
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
消费者
spring:
application:
name: eureka-client-order-consumer-service
server:
port: 8082
eureka:
client:
serviceUrl:
defaultZone: http://yangle:123@localhost:8761/eureka,http://yangle:123@localhost:8762/eureka
instance:
preferIpAddress: true
instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
Add a new registration center address and register services to two registration centers at the same time
Restart, verify function
! ! ! This is the end of the actual combat function, and then add some theoretical knowledge to yourself
The difference between zookeeper and eureka
Because there is a well-known CAP theory in the distributed field, it is impossible for the three to exist at the same time. What do AP, CP and CAP represent?
C: Consistency
A: Availability
P: Partition fault tolerance
Now let’s talk about why CAPs can’t coexist at the same time, because if you want to ensure data consistency, you must lock the data and stop generating new data when the data is synchronized to other nodes. At this time, new requests will be rejected Or leave the user in a blocked waiting state, release only after the synchronization is completed, receive or process new requests, which will cause unavailability of the service, and if the availability of the service is guaranteed, then the data synchronization Locking operations cannot be performed at the time, which conflicts with the necessary conditions of data consistency. This is the meta-infant that CA is not mutually soluble. Some people will say that P, P must exist, because if it is a cluster, then P must exist.
Let’s talk about the difference between zookeeper and eureka. Zookeeper is based on CP and discards A. He often combines with DUBBO. EUREKA emphasizes AP. Consistency
Content quoted from: https://blog.csdn.net/alan_gaohaodong/article/details/82899413
Zookeeper guarantees the CP principle:
1.1 When querying the service list from the registration center, we can tolerate that the registration center returns the registration information a few minutes ago,
but it cannot accept the service directly down and unavailable. In other words, the service registration function has higher requirements for availability than consistency.
But zk will have this kind of situation, when the master node loses contact with other nodes due to a network failure, the remaining registration
function will restart the leader election. The problem is that the leader election time is too long, 30~120s, and the
entire zk cluster is unavailable during the election, which leads to the paralysis of registration services during the election. In a cloud deployment environment,
it is a high probability that the zk cluster will lose the master node due to network problems . Although the service can eventually be restored, the long
-term unavailability of registration caused by the long election time is intolerable.
1.2 Eureka understands this, and therefore prioritizes usability during design. All nodes of Eureka are equal
, and the failure of several nodes will not affect the work of normal nodes, and the remaining nodes can still provide registration and query services.
When the Eureka client registers with an Eureka or if it finds that the link fails, it will automatically switch to other nodes.
As long as one Eureka is still there, the registration service can be guaranteed to be available (guaranteed to be available), but the information is found May not be
up to date (consistency is not guaranteed). In addition, Eureka also has a self-protection mechanism. If more than 85%
of the nodes do not have a normal heartbeat within 15 minutes , then Eureka believes that there is a network failure between the client and the registry. At this time, there will be
several situations. :
(1) Eureka will not remove from the registration list the service that should expire because it has not received a heartbeat for a long time.
(2) Eureka can still accept new service registration and query requests, but it will not be synchronized to other nodes
(guarantee the current node still available)
(3) when the network is stable, the current instance of the new registration information will be synchronized to other nodes
and therefore, Eureka can well cope with the situation due to network failure resulting in some nodes lost contact, but did not like zk
is The entire registration service is paralyzed.
About eureka interview questions and answers
1. Introduce CAP
The answer is as above
2. The difference between EUREKA and zookeeper
The answer is as above
to sum up
Through the introduction of this chapter, I understand what a registry is, and it has been able to provide a framework for registry functions. Then I introduced the entry-level use of eureka and how to ensure the high availability of the eureka registry. Finally, I discussed the difference between zookeeper and eureka and the common interview For the question about eureka, I will continue to explain the related knowledge of springcloud later, and the next section will introduce how to implement load balancing on the client.
Welcome everyone to pay attention to my official account, reply to eureka, get the source code of this chapter, reply to "receive information", get more learning video materials such as artificial intelligence, big data, etc. If there is any infringement, please contact the author to delete it immediately!