Summary of SpringCloud study notes (2)

Git code address: https://gitee.com/it-sherlock/java-project-template .

1. Eureka Basics of Eureka


Eureka is used as a server for service registration and discovery functions.

Eureka has been replaced by other services, but there are still old projects that use Eureka.

Architecture comparison of Eureka and Dubbo:
insert image description here


Two components of Eureka: Eureka Server and Eureka Client.

insert image description here

2. Eureka Server installation of Eureka


Build the red part of the picture below:
insert image description here


Step 1: Create a springboot project as the Eureka Server server, and import the eureka-server server jar package into the cloud-eureka-server7001 project.

 <!--导入eureka-server服务端的jar包-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

Step 2: Configure application.yaml and configure the relevant information of the corresponding eureka-server.

server:
  port: 7001

eureka:
  instance:
    hostname: localhost # eureka服务端的实例名称
  client:
    # false表示不向注册中心注册自己(本身这个项目就是注册中心,没必要注册自己)
    register-with-eureka: false
    # false表示自己端就是注册中心,该项目的职责就是维护服务实例,并不需要检索服务。
    fetch-registry: false
    service-url:
      # 设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://${
    
    eureka.instance.hostname}:${
    
    server.port}/eureka/

Step 3: The @EnableEurekaServer annotation indicates that the EurekaServer service is started.

package com.itholmes.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@SpringBootApplication
@EnableEurekaServer
public class EurekaMain7001 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(EurekaMain7001.class,args);
    }
}

Step 4: Test Eurake Server, start the project, access the corresponding path, and you can view the web page of Eurake Server, indicating success!
insert image description here

3. Eureka will move other projects into Eureka Server


After the Eureka Server server is configured, it is equivalent to the Eureka Client client for other projects.

The first step: Add the dependency package of netflix-eureka-client (note that there are many different versions of eureka, the imported package should correspond to it!).

insert image description here

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

Step 2: Add the @EnableEurekaClient annotation to the SpringBoot startup class.

Step 3: Modify the application.yml configuration.

server:
  port: 8001

spring:
  application:
    # 微服务的注册名称,这个与注册中心有关系!
    name: cloud-payment-service

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    # 是否从eurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    # 入驻地址是哪个
    service-url:
      defaultZone: http://localhost:7001/eureka

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.itholmes.springcloud.entities # 所有Entity别名类所在包

Step 4: Start the test. When starting, start eureka Server first, and then start the client!
insert image description here

As can be seen from the above figure, in fact, Eureka Server stores the form of key-value, the key is the microservice application name (service alias), and the value is the corresponding address.


What the following code does:

spring:
  application:
    name: cloud-payment-service

If you are a microservice, it acts as a unique identifier (otherwise, how do you let the registry know which service instance you registered logically belongs to)
insert image description here
insert image description here


yml format indentation error attention! ! !
insert image description here

4. Eureka builds Eureka cluster


By building the Eureka registry cluster, load balancing and fault tolerance are realized!

At this time, multiple eureka server projects are required.

Configure multiple eureka server projects. The principle of clustering is: 相互注册,相互守望.

insert image description here

The first step: 相互注册,相互守望configure each EurekaServer with each other!

  • The following defaultZone: xxx configures the addresses of other EurekaServers.
server:
  port: 7002 # 这里是7002端口的eureka 下面就要注册上eureka7001的eureka地址。

eureka:
  instance:
    hostname: eureka7002.com # eureka服务端的实例名称
  client:
    # false表示不向注册中心注册自己(本身这个项目就是注册中心,没必要注册自己)
    register-with-eureka: false
    # false表示自己端就是注册中心,该项目的职责就是维护服务实例,并不需要检索服务。
    fetch-registry: false
    service-url:
      # 设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://eureka7001.com:7001/eureka/

insert image description here

Step 2: Register each microservice with the Eureke cluster.

  • Only two are listed below.
eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    # 是否从eurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    # 入驻地址是哪个
    service-url:
      # defaultZone: http://localhost:7001/eureka # 单机
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群配置

The third step: test, start.

5. Eureka builds business logic cluster


Create two springboot microservice projects with the same business logic, to 注意他们端口号不同,但是微服务名称(spring.application.name相同!).

insert image description here

At the same time, they are all registered in the eureka server, so that when we enter the eureka web page, we can see that there are two registration addresses under the corresponding microservice application name:
insert image description here

In this way, we can write a special project to associate it with the eureka server and act as a transitioner for sending requests:

This is the consumer-order80 project, through which other projects can be accessed, so that the server of the business logic cluster can be accessed through the microservice application name registered in the eureka server.
insert image description here

code show as below:

package com.itholmes.springcloud.controller;

import com.itholmes.springcloud.entities.CommonResult;
import com.itholmes.springcloud.entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
@Slf4j
public class OrderController {
    
    

    /**
     * 因为这里我们发起了restemplate请求来访问对应地址。
     * 现在业务逻辑层是集群效果,因此这里不能固定访问一个地址去。
     *      通过访问eureka注册的微服务应用名称来解决。
     */
    //public static final String PAYMENT_URL = "http://localhost:8001"; 这只会访问一个地址。
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    RestTemplate restTemplate;

    @GetMapping("/consumer/payment/create")
    public CommonResult<Payment> create(Payment payment){
    
    
        return restTemplate.postForObject(PAYMENT_URL+"/payment/create",payment,CommonResult.class);
    }

    @RequestMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") Long id){
    
    
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
    }

}

In addition, we also need to load an annotation @LoadBalanced to the RestTemplate object in the ioc container:

  • Use the @LoadBalanced annotation to give RestTemplate load balancing capabilities (RestTemplate has client-side load balancing capabilities).
package com.itholmes.springcloud.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

//给ioc容器添加restTemplate对象。
@Configuration
public class ApplicationContextConfig {
    
    
    @Bean
    @LoadBalanced //使用@LoadBalanced注解赋予RestTemplate负载均衡的能力
    public RestTemplate getRestTemplate(){
    
    
        return new RestTemplate();
    }
}

When building eureka here, the host name of my local account is IT_holmes, because the ' _ ' symbol causes the domain name to report an error and cannot be accessed, be sure to pay attention!
insert image description here

Solution:

  • You can modify instance-id, name.
  • Detailed address: https://blog.csdn.net/mango5208/article/details/107208637.
eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    # 是否从eurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    # 入驻地址是哪个
    service-url:
      # defaultZone: http://localhost:7001/eureka # 单机
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群配置
  
  # 这里不配置默认是主机的名字,如果主机名有下划线_符号可能就不会访问!!!
  instance:
    instance-id: ITholmes:cloud-provider-payment:8002
    # 访问路径可以显示IP地址
    prefer-ip-address: true

insert image description here

6. Eureka's actuator microservice information is perfect


The two dependencies spring-boot-starter-web and spring-boot-starter-actuator are indispensable here!

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

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

Actuator is a functional module provided by Springboot to introspect and monitor the application system. With the help of Actuator, developers can easily view and count some monitoring indicators of the application system.

/actuator/health, the health check of the actuator:
insert image description here

instance-id Modify the configuration host name:

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    # 是否从eurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    # 入驻地址是哪个
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      #defaultZone: http://localhost:7001/eureka #单机版
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka  #集群版

  # 这里不配置默认是主机的名字,如果主机有下划线_符号可能就不会访问!!!
  instance:
    instance-id: ITholmes:cloud-order-service:80
    # 访问路径可以显示IP地址
    prefer-ip-address: true

prefer-ip-address: true , when accessible, the IP address can be displayed:
insert image description here

7. SpringCloud's service discovery Discovery (emphasis)


For microservices registered in eureka, the service information can be obtained through service discovery:

Step 1: Add @EnableDiscoveryClient //Enable service discovery client annotation in the business logic startup class.

package com.itholmes.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient //开启服务发现客户端
public class PaymentMain8001 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(PaymentMain8001.class,args);
    }
}

Under the corresponding controller layer, import the corresponding DiscoveryClient:

import org.springframework.cloud.client.discovery.DiscoveryClient;

@Resource
private DiscoveryClient discoveryClient;

@GetMapping(value = "/payment/discovery")
public Object discovery(){
    
    

    //获取eureka 服务列表的service信息,就是注册在eureka的全部微服务应用名称。
    List<String> services = discoveryClient.getServices();
    for (String element : services) {
    
    
        log.info("****element:"+element);
    }

    //获取eureka对应一个微服务应用名下面的全部个体实例。
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    for (ServiceInstance instance : instances) {
    
    
        log.info(instance.getServiceId()+"\t"+instance.getHost()+"\t"+instance.getPort()+"\t"+instance.getUri());
    }

    return this.discoveryClient;
}

insert image description here
insert image description here

8. Eureka's Self-Protection


insert image description here
That is, when a microservice is unavailable at a certain moment, Eureka will not clean it up immediately, and will still save the information of the microservice.
insert image description here
insert image description here

Here is an AP branch idea in CAP.


How to disable Eureka's self-protection?

  • Eureka turns on self-protection by default.

The Eureka server server configuration is as follows:

  • Use server.enable-self-preservation:false to turn off self-preservation.
server:
  port: 7001

eureka:
  instance:
    hostname: eureka7001.com # eureka服务端的实例名称
  client:
    # false表示不向注册中心注册自己(本身这个项目就是注册中心,没必要注册自己)
    register-with-eureka: false
    # false表示自己端就是注册中心,该项目的职责就是维护服务实例,并不需要检索服务。
    fetch-registry: false
    service-url:
      # 设置与Eureka Server交互的地址查询服务和注册服务都需要依赖这个地址。
      defaultZone: http://eureka7002.com:7002/eureka/

  # 关闭自我保护机制,保证不可用服务被即使剔除。
  server:
    enable-self-preservation: false

The eureka client configuration is as follows:

  • lease-renewal-interval-in-seconds: 1 # The time interval for Eureka client to send heartbeat to server, in seconds (default is 30 seconds).
  • lease-expiration-duration-in-seconds: 2 # The upper limit of the waiting time for the Eureka server to wait after receiving the last heartbeat, in seconds (the default is 90 seconds), and the service will be eliminated by timeout.
server:
  port: 8001

spring:
  application:
    # eureka注册后的名字
    name: cloud-payment-service
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://rm-bp168t05xk88zzbv7ro.mysql.rds.aliyuncs.com/db2019?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&useSSL=true
    username: root
    password: XuYanBo0818

eureka:
  client:
    # 表示是否将自己注册进EurekaServer默认为true
    register-with-eureka: true
    # 是否从eurekaServer抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    # 入驻地址是哪个
    service-url:
      # defaultZone: http://localhost:7001/eureka # 单机
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群配置

  # 这里不配置默认是主机的名字,如果主机有下划线_符号可能就不会访问!!!
  instance:
    instance-id: payment8001
    # 访问路径可以显示IP地址
    prefer-ip-address: true

    # Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
    lease-renewal-interval-in-seconds: 1
    # Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒) 超时剔除服务
    lease-expiration-duration-in-seconds: 2

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.itholmes.springcloud.entities # 所有Entity别名类所在包

In this way, once the microservice in the eureka service is down, the service will be removed immediately after the configuration time.
insert image description here

9. Description of Eureka's discontinuation


https://github.com/Netflix/eureka Eureka official.

eureka server has stopped updating.

Guess you like

Origin blog.csdn.net/IT_Holmes/article/details/125243564