Spring cloud notes: Basics

Posted by fernado1283 on Wed, 19 Jan 2022 09:21:07 +0100

1. Today's content

  • Getting to know Spring Cloud
  • Spring Cloud service governance

2. Get to know Spring Cloud

2.1 - micro service architecture

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-5Ex5oAyD-1626660797174)(img/1587520885330.png)]

Microservice architecture:
The word "Microservices" comes from Martin Fowler's blog post called Microservices, which can be found on his official blog
http://martinfowler.com/articles/microservices.html

  • Microservice is a design style of system architecture. Its main purpose is to split an originally independent system into multiple small services. These small services run in their own independent processes. Services generally communicate and cooperate through HTTP RESTfuLAPI.

  • Each small service is built around one or more business functions with high coupling in the system, and each service maintains its own data storage, business development automation test cases and independent deployment machines
    System.

  • With a lightweight communication and collaboration foundation, these microservices can be used
    Written in different languages.

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-f3GP4dQv-1626660797176)(img/1587521016035.png)]

2.2 - getting to know Spring Cloud

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tAhk1ms0-1626660797177)(img/1587521103729.png)]

  • Spring Cloud is an ordered collection of frameworks.

  • Spring Cloud does not repeatedly manufacture wheels. It just combines the more mature and practical service frameworks developed by various companies.

  • Repackaging in Spring Boot style shields the complex configuration and implementation principles, and finally leaves a set of simple, easy to understand, easy to deploy and easy to maintain distributed system development kit for developers.

  • Taking advantage of the development convenience of Spring Boot, it cleverly simplifies the development of distributed system infrastructure, such as service discovery and registration, configuration center, message bus, load balancing, circuit breaker, data monitoring, etc., which can be started and deployed with one click with the development style of Spring Boot.

  • Spring Cloud project official website: https://spring.io/projects/spring-cloud

  • The naming method of Spring Cloud version adopts the name of London underground station, and corresponds to the version time order according to the alphabet. For example, the earliest Release version is Angel, the second Release version is Brixton, and then Camden, Dalton, Edgware, Finchley, Greenwich and Hoxton.

  • The latest version is Hoxton.

    [the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-E0o87tUK-1626660797179)(img/1587521364642.png)]

2.3 comparison between spring cloud and dubbo

[the external link picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ykvYwNBa-1626660797181)(img/1587521416722.png)]

Comparison between Spring Cloud and dubbo

  • Both Spring Cloud and Dubbo are effective tools for implementing microservices.

  • Dubbo only implements service governance, while the Spring Cloud subproject covers many components under the micro service architecture.

  • Dubbo uses RPC communication protocol and Spring Cloud uses RESTful to complete communication. Dubbo is slightly more efficient than Spring Cloud.

summary

  • Microservice is to split each module of the project into an architecture design style that can be run, deployed and tested independently.

  • Spring company integrates the components commonly used in microservice architecture in other companies, and uses SpringBoot to simplify its development and configuration.

    Called Spring Cloud

  • Both Spring Cloud and Dubbo are effective tools for implementing microservices. Dubbo has better performance and Spring Cloud is more comprehensive.

3.Spring Cloud service governance

3.1 introduction to Eureka

• Eureka is an open source service registration and discovery component of Netflix.

• Eureka and other Netflix service components (such as load balancing, fuses, gateways, etc.) are integrated into the Spring Cloud community
Spring cloud Netflix module.

• Eureka consists of two components: Eureka Server (Registry) and Eureka Client (service provider and service consumer).

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-uitm18jw-1626660797181)(img/1587521790834.png)]

Eureka learning steps

  1. Set up Provider and Consumer services.
  2. Use RestTemplate to complete the remote call.
  3. Set up Eureka Server service.
  4. The Provider and Consumer are called Eureka Client.
  5. The Consumer service grabs the Provider from Eureka Server
    Address complete remote call

3.2-Eureka quick start

3.2.1 - environment construction

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-RsJfhr0M-1626660797182)(img/1587966687575.png)]

3.2.1.1 - create parent project

Create module - parent project spring cloud parent

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-pb8zXZcX-1626660797183)(img/1587522395375.png)]

  • Directory structure after creation (delete src)

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jaQOONzF-1626660797183)(img/1587522452309.png)]

Spring-cloud-parent pom.xml

   <!--spring boot environment -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>


    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

3.2.1.2 - create a service provider

  • Create service provider Eureka provider

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wBnxrexn-1626660797184)(img/1587522728754.png)]

eureka-provider pom.xml

    <dependencies>

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

    </dependencies>

GoodsController

package com.itheima.provider.controller;

import com.itheima.provider.domain.Goods;
import com.itheima.provider.service.GoodsService;
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;

/**
 * Goods Controller service provider 
 */

@RestController
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/findOne/{id}")
    public Goods findOne(@PathVariable("id") int id){

        Goods goods = goodsService.findOne(id);

        return goods;
    }
}

GoodsService

package com.itheima.provider.service;

import com.itheima.provider.dao.GoodsDao;
import com.itheima.provider.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Goods Business layer
 */
@Service
public class GoodsService {

    @Autowired
    private GoodsDao goodsDao;


    /**
     * Query by id
     * @param id
     * @return
     */
    public Goods findOne(int id){
        return goodsDao.findOne(id);
    }
}

Goods

package com.itheima.provider.domain;

/**
 * Commodity entity class
 */
public class Goods {

    private int id;
    private String title;//Product title
    private double price;//commodity price
    private int count;//Commodity inventory

    public Goods() {
    }

    public Goods(int id, String title, double price, int count) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.count = count;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

GoodsDao

package com.itheima.provider.dao;

import com.itheima.provider.domain.Goods;
import org.springframework.stereotype.Repository;

import javax.validation.ReportAsSingleViolation;

/**
 * Commodity Dao
 */

@Repository
public class GoodsDao {


    public Goods findOne(int id){
        return new Goods(1,"Huawei mobile phone",3999,10000);
    }
}

ProviderApp

package com.itheima.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Startup class
 */

@SpringBootApplication
public class ProviderApp {


    public static void main(String[] args) {
        SpringApplication.run(ProviderApp.class,args);
    }
}

application.yml

server:
  port: 8000

3.2.1.2 - creating service consumers

  • Create a service consumer Eureka consumer

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-t1S5lDzx-1626660797184)(img/1587522756792.png)]

  • Final directory structure

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-82Az4TrZ-1626660797185)(img/1587522649367.png)]

OrderController

package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
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;


/**
 * Caller of the service
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);


		//Remotely call the findOne interface in the Goods service
        return null;
    }
}

Goods

package com.itheima.consumer.domain;

/**
 * Commodity entity class
 */
public class Goods {

    private int id;
    private String title;//Product title
    private double price;//commodity price
    private int count;//Commodity inventory

    public Goods() {
    }

    public Goods(int id, String title, double price, int count) {
        this.id = id;
        this.title = title;
        this.price = price;
        this.count = count;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

ConsumerApp

package com.itheima.consumer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApp {


    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

application.yml

server:
  port: 9000

3.2.2-RestTemplate remote call

• Spring provides a simple and convenient template class for accessing restful services in java code.
• its function is similar to HttpClient, but RestTemplate is more elegant and convenient to use.

Modify consumer code

RestTemplateConfig

package com.itheima.consumer.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.client.RestTemplate;@Configurationpublic class RestTemplateConfig {    @Bean    public RestTemplate restTemplate(){        return new RestTemplate();    }}

OrderController

package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
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;

/**
 * Caller of the service
 */

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);
        /*
            //Remotely call the findOne interface in the Goods service
            Using RestTemplate
            1. Define bean resttemplate
            2. Inject Bean
            3. Call method
         */

        String url = "http://localhost:8000/goods/findOne/"+id;
        // 3. Call method
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;
    }
}

3.2.3- Eureka Server setup

① Create Eureka server module

② Introduce spring cloud and euraka server related dependencies

Spring-cloud-parent pom.xml

<properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>        <java.version>1.8</java.version>        <!--spring cloud edition-->        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>    </properties>    <!--introduce Spring Cloud rely on-->    <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>

eureka-server pom.xml

 <dependencies>

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

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

EurekaApp

package com.itheima.eureka;

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

@SpringBootApplication
// Enable EurekaServer
@EnableEurekaServer
public class EurekaApp {

    public static void main(String[] args) {
        SpringApplication.run(EurekaApp.class,args);
    }
}

③ Complete Eureka Server configuration

application.yml

server:
  port: 8761

# eureka configuration
# eureka has four configurations
# 1. dashboard:eureka's web console configuration
# 2. Server: server configuration of Eureka
# 3. client:eureka's client configuration
# 4. Instance: instance configuration of Eureka


eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka # eureka server address. The client will use this address to communicate with eureka in the future

    register-with-eureka: false # Whether to register your path to eureka. Not required by eureka server, but required by eureka provider client
    fetch-registry: false # Whether to grab the path from eureka. Not required by eureka server, but required by eureka consumer client

④ Start the module

3.2.4 introduction to Eureka console

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-HVnO7Q2e-1626660797186)(img/1587524898190.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ng6FET2f-1626660797186)(img/1587524966009.png)]

System status: system status information

DS Replicas: cluster information

tance currently registered with Eureka: instance registration information

General Info: general information

Instance Info: instance information

3.2.5-Eureka Client

① Introduce Eureka client dependency

eureka-provider pom.xml

  <dependencies>

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

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

    </dependencies>

ProviderApp

package com.itheima.provider;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;/** * Startup class */@EnableEurekaClient //The annotation can omit @ springbootapplicationpublic class providerapp {public static void main (string [] args) {springapplication.run (providerapp. Class, args);}}

② Complete the configuration of eureka client

application.yml

server:  port: 8001eureka:  instance:    hostname: localhost # host name  client:    service-url:      defaultZone: http://localhost:8761/eureka # eureka server address. The client will use this address to communicate with eureka in the future. Spring: Application: Name: eureka provider # set the name of the current Application. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future

③ Start test

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Es68EboS-1626660797187)(img/1587525778719.png)]

The service consumer Eureka consumer can also be displayed on the console through modification

Here, Eureka consumer is only defined as a consumer. As a service, it can be both a service provider and a service consumer

ConsumerApp add @ EnableEurekaClient

package com.itheima.consumer;

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;


@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {


    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

application.yml

server:
  port: 9000


eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka # eureka server address. The client will use this address to communicate with eureka in the future
spring:
  application:
    name: eureka-consumer # Sets the name of the current app. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-uqkaynKl-1626660797187)(img/1587526247520.png)]

3.2.6 - dynamic acquisition path

ConsumerApp add @ EnableDiscoveryClient

package com.itheima.consumer;

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;

@EnableDiscoveryClient // Activate DiscoveryClient
@EnableEurekaClient
@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApp.class,args);
    }
}

The OrderController modifies the code to dynamically obtain the path

package com.itheima.consumer.controller;


import com.itheima.consumer.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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 java.util.List;

/**
 * Caller of the service
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        System.out.println("findGoodsById..."+id);


        /*
            //Remotely call the findOne interface in the Goods service
            Using RestTemplate
            1. Define bean resttemplate
            2. Inject Bean
            3. Call method
         */

        /*
            Dynamically obtain the ip and port of the provider from Eureka Server
             1. Inject the DiscoveryClient object activation
             2. Call method
         */

        //Demonstrate the use of discoveryClient
       List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA-PROVIDER");

        //Determine whether the set has data
        if(instances == null || instances.size() == 0){
            //The collection has no data
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();//Get ip
        int port = instance.getPort();//Get port

        System.out.println(host);
        System.out.println(port);

        String url = "http://"+host+":"+port+"/goods/findOne/"+id;
        // 3. Call method
        Goods goods = restTemplate.getForObject(url, Goods.class);


        return goods;
    }
}

3.3-Eureka properties

3.3.1 instance related attributes

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Bc0C2h7A-1626660797188)(img/1587969318191.png)]

All the configuration information of Eureka Instance is saved at org.org springframework. cloud. netflix. eureka. In the eurekainstanceconfigbean configuration class, it is actually com netflix. appinfo. The implementation class of eurekainstanceconfig replaces Netflix's com netflix. appinfo. The default implementation of cloudinstanceconfig.

The configuration information of Eureka Instance is based on Eureka Instance. Format configuration of XXX.

Configuration list

  • appname = unknown

Application name, first get spring application. The value of name. If the value is blank, the default value is unknown.

  • appGroupName = null

Application group name

  • instanceEnabledOnit = false

If the instance is registered to Eureka, whether to start communication immediately. Sometimes applications need some preprocessing before preparing services.

  • nonSecurePort = 80

Non secure port

  • securePort = 443

Secure port

  • nonSecurePortEnabled = true

Enable non secure port communication

  • securePortEnabled = false

Enable secure port communication

  • leaseRenewalIntervalInSeconds = 30

Instance renewal interval

  • leaseExpirationDurationInSeconds = 90

Instance timeout, which means that the maximum leaseExpirationDurationInSeconds is not renewed after seconds. The Server considers it unavailable and will eliminate it.

  • virtualHostName = unknown

Virtual host name, first get spring application. The value of name. If the value is blank, the default value is unknown.

  • instanceId

The unique instance ID registered on eureka cannot be duplicated with other instances of the same appname.

  • secureVirtualHostName = unknown

Secure virtual host name, first get spring application. The value of name. If the value is blank, the default value is unknown.

  • metadataMap = new HashMap();

Instance metadata, which can be used by other instances. For example, spring boot admin obtains the context and port of the instance during monitoring.

  • dataCenterInfo = new MyDataCenterInfo(DataCenterInfo.Name.MyOwn);

Data center for instance deployment. Such as AWS and MyOwn.

  • ipAddress=null

IP address of the instance

  • statusPageUrlPath = "/actuator/info"

Instance status page relative url

  • statusPageUrl = null

Instance status page absolute URL

  • homePageUrlPath = "/"

Instance home page relative URL

  • homePageUrl = null

Instance home page absolute URL

  • healthCheckUrlUrlPath = "/actuator/health"

Instance health check relative URL

  • healthCheckUrl = null

Instance health check absolute URL

  • secureHealthCheckUrl = null

Absolute URL of health check for instance security

  • namespace = "eureka"

Namespace of configuration property (ignored in Spring Cloud)

  • hostname = null

The host name is obtained according to the host name of the operating system when it is not configured

  • preferIpAddress = false

Do you prefer to use IP address as the identification of host name

3.3.1 server related properties

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9mp1B372-1626660797189)(img/1587526704046.png)]

The configuration of Eureka Server registry is the feature configuration of the registry. Eureka Server is fully configured at org springframework. cloud. netflix. eureka. server. Eurekaserverconfigbean is actually com netflix. eureka. The implementation class of eurekaserverconfig replaces the default implementation of Netflix.

Eureka Server configuration is based on Eureka Server. XXX format.

Configuration list

  • enableSelfPreservation=true

Turn on self-protection

  • renewalPercentThreshold = 0.85

Self protection renewal percentage threshold factor. If the actual number of renewals is less than the threshold number of renewals, turn on self-protection

  • renewalThresholdUpdateIntervalMs = 15 * 60 * 1000

Continued divisor threshold update frequency.

  • peerEurekaNodesUpdateIntervalMs = 10 * 60 * 1000

Update frequency of Eureka Server nodes.

  • enableReplicatedRequestCompression = false

Whether replication request compression is enabled.

  • waitTimeInMsWhenSyncEmpty=5 * 60 * 1000

The waiting time when the synchronization instance information from other nodes is empty.

  • peerNodeConnectTimeoutMs=200

Timeout for connections between nodes.

  • peerNodeReadTimeoutMs=200

Timeout for reading information between nodes.

  • peerNodeTotalConnections=1000

Total number of connections between nodes.

  • peerNodeTotalConnectionsPerHost = 500;

The total number of connections between individual nodes.

  • peerNodeConnectionIdleTimeoutSeconds = 30;

Inter node connection idle timeout.

  • retentionTimeInMSInDeltaQueue = 3 * MINUTES;

Cache time of the incremental queue.

  • deltaRetentionTimerIntervalInMs = 30 * 1000;

Frequency of expiration in the cleanup delta queue.

  • evictionIntervalTimerInMs = 60 * 1000;

Eliminate task frequency.

  • responseCacheAutoExpirationInSeconds = 180;

Registration list cache timeout (when the registration list does not change)

  • responseCacheUpdateIntervalMs = 30 * 1000;

Register list cache update frequency.

  • useReadOnlyResponseCache = true;

Whether to enable the L2 cache of the registration list.

  • disableDelta=false.

Whether to provide incremental information for the client.

  • maxThreadsForStatusReplication = 1;

Maximum number of threads for state synchronization.

  • maxElementsInStatusReplicationPool = 10000;

Maximum capacity of the status synchronization queue.

  • syncWhenTimestampDiffers = true;

Whether to synchronize when there is a time difference.

  • registrySyncRetries = 0;

Number of registration information synchronization retries.

  • registrySyncRetryWaitMs = 30 * 1000;

The time interval between registration information synchronization retries.

  • maxElementsInPeerReplicationPool = 10000;

Maximum capacity of synchronization events between nodes.

  • minThreadsForPeerReplication = 5;

Minimum number of threads synchronized between nodes.

  • maxThreadsForPeerReplication = 20;

Maximum number of threads synchronized between nodes.

  • maxTimeForReplication = 30000;

The maximum synchronization time between nodes, in milliseconds.

  • disableDeltaForRemoteRegions = false;

Whether to enable remote area increment.

  • remoteRegionConnectTimeoutMs = 1000;

Remote area connection timeout.

  • remoteRegionReadTimeoutMs = 1000;

Remote area read timeout.

  • remoteRegionTotalConnections = 1000;

Maximum connections in remote area

  • remoteRegionTotalConnectionsPerHost = 500;

Number of stand-alone connections in remote area

  • remoteRegionConnectionIdleTimeoutSeconds = 30;

Remote area connection idle timeout.

  • remoteRegionRegistryFetchInterval = 30;

Remote area registration information pull frequency.

  • remoteRegionFetchThreadPoolSize = 20;

Number of remote zone registration information threads.

3.4-Eureka high availability

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-05i6V4f8-1626660797189)(img/1587526769913.png)]

  1. Prepare two Eureka servers
  2. Configure separately and register with each other
  3. Eureka Client is registered in these two Eureka servers

3.4.1 - erection

Create eureka-server-1

pom.xml

    <dependencies>

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

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

    </dependencies>

application.yml

server:
  port: 8761


eureka:
  instance:
    hostname: eureka-server1 # host name
  client:
    service-url:
      defaultZone: http://eureka-server2:8762/eureka
    register-with-eureka: true # Whether to register your path to eureka. Not required by eureka server, but required by eureka provider client
    fetch-registry: true # Whether to grab the path from eureka. Not required by eureka server, but required by eureka consumer client


spring:
  application:
    name: eureka-server-ha

Eureka1App

package eureka;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@SpringBootApplication// Enable EurekaServer@EnableEurekaServerpublic  class Eureka1App {    public static void main(String[] args) {        SpringApplication.run(Eureka1App.class,args);    }}

Create eureka-server-2

pom.xml

    <dependencies>

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

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

    </dependencies>

application.yml

server:
  port: 8762


eureka:
  instance:
    hostname: eureka-server2 # host name
  client:
    service-url:
      defaultZone: http://eureka-server1:8761/eureka

    register-with-eureka: true # Whether to register your path to eureka. Not required by eureka server, but required by eureka provider client
    fetch-registry: true # Whether to grab the path from eureka. Not required by eureka server, but required by eureka consumer client
spring:
  application:
    name: eureka-server-ha

Eureka2App

package eureka;

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

@SpringBootApplication
// Enable EurekaServer
@EnableEurekaServer
public class Eureka2App {

    public static void main(String[] args) {
        SpringApplication.run(Eureka2App.class,args);

    }
}

Modify local host

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-tFDDA9HG-1626660797190)(img/1587970377083.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Ay8ADKDK-1626660797190)(img/1587527469782.png)]

3.4.2 - client test

Modify the registered service address in the service provider and service consumer profiles

eureka-provider application.yml

server:
  port: 8001


eureka:
  instance:
    hostname: localhost # host name
    prefer-ip-address: true # Register the ip of the current instance with eureka server. The default is false to register the host name
    ip-address: 127.0.0.1 # Set the ip address of the current instance
    instance-id: ${eureka.instance.ip-address}:${spring.application.name}:${server.port} # Set the instance id displayed on the web console
    lease-renewal-interval-in-seconds: 3 # Send a heartbeat packet every 3 seconds
    lease-expiration-duration-in-seconds: 9 # If you don't send a heartbeat packet in 9 seconds, the server, you kill me~
  client:
    service-url:
      defaultZone: http://eureka-server1:8761/eureka, http://eureka-server2:8762/eureka #Eureka server address, which will be used by clients to communicate with Eureka in the future
spring:
  application:
    name: eureka-provider # Sets the name of the current app. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future


eureka-consumer application.yml

server:
  port: 9000


eureka:
  instance:
    hostname: localhost # host name
  client:
    service-url:
      defaultZone:  http://eureka-server1:8761/eureka, http://eureka-server2:8762/eureka #Eureka server address, which will be used by clients to communicate with Eureka in the future
spring:
  application:
    name: eureka-consumer # Sets the name of the current app. It will be displayed in eureka Application in the future. You will need to use this name to get the path in the future

test result
[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3zNoYJ5P-1626660797191)(img/1587527850803.png)]

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-vQ91LnZN-1626660797191)(img/1587527811851.png)]

3.5-Consul

3.5.1-Consul overview

Consul is developed by HashiCorp based on Go language. It supports multi data center, distributed and highly available service publishing and registration service software.
• service discovery and configuration for distributed systems.
• easy to use. It has natural portability (supports Linux, windows and Mac OS X); The installation package contains only one executable,
Easy deployment.
• official website address: https://www.consul.io

Start consumer

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-11QRdhI5-1626660797192)(img/1587528140341.png)]

dev mode: no persistent data

Start successful

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3zoDv0Qb-1626660797192)(img/1587528221446.png)]

Console

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-GdI7n8GW-1626660797193)(img/1587528280115.png)]

3.5.2-consult quick start

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-xvfhf4q-1626660797193) (IMG / 1587527962928. PNG)]

  1. Set up Provider and Consumer services.
  2. Use RestTemplate to complete the remote call.
  3. Register the Provider service in consult.
  4. The Consumer service grabs the Provider from the Consumer
    Address complete remote call

Provider pom.xml

<dependencies>        <!--consul client-->        <dependency>            <groupId>org.springframework.cloud</groupId>            <artifactId>spring-cloud-starter-consul-discovery</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>        </dependency>        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-actuator</artifactId>        </dependency>    </dependencies>

application.yml

server:  port: 8000spring:  cloud:    consul:      host: localhost # consul Server side ip      port: 8500 # consul The server port is 8500 by default      discovery:        service-name: ${spring.application.name} # Current app registered to consul Name of        prefer-ip-address: true # register ip  application:    name: consul-provider # apply name

consumer pom.xml

<dependencies>
        <!--consul client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</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>
        </dependency>

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

    </dependencies>

application.yml

server:
  port: 9000


spring:
  cloud:
    consul:
      host: localhost # The ip address of the consumer server
      port: 8500 # The default port of the consumer server is 8500
      discovery:
        service-name: ${spring.application.name} # The name of the current app registered to consumer
        prefer-ip-address: true # Register ip

  application:
    name: consul-consumer # apply name

OrderController

package com.itheima.consul.controller;


import com.itheima.consul.domain.Goods;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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 java.util.List;

/**
 * Caller of the service
 */

@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable("id") int id){
        //Demonstrate the use of discoveryClient
        List<ServiceInstance> instances = discoveryClient.getInstances("consul-PROVIDER");

        //Determine whether the set has data
        if(instances == null || instances.size() == 0){
            //The collection has no data
            return null;
        }

        ServiceInstance instance = instances.get(0);
        String host = instance.getHost();//Get ip
        int port = instance.getPort();//Get port

        System.out.println(host);
        System.out.println(port);

        String url = "http://"+host+":"+port+"/goods/findOne/"+id;
        // 3. Call method
        Goods goods = restTemplate.getForObject(url, Goods.class);


        return goods;
    }
}

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-P1RxZotj-1626660797194)(img/1587538853089.png)]

3.6-Nacos

3.6.1 overview of Nacos

Nacos (Dynamic Naming and Configuration Service) is an open source project of Alibaba in July 2018.
• it focuses on service discovery and configuration management, and is committed to helping you discover, configure and manage microservices. Nacos supports almost all mainstream types of "service"
Discovery, configuration and management of "service".
• in one sentence, Nacos = Spring Cloud registry + Spring Cloud configuration center.
• official website: https://nacos.io/
• download address: https://github.com/alibaba/nacos/releases

start-up

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-iJ97GpYP-1626660797195)(img/1587539022443.png)]

Successful startup effect:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-SmAYgZ9F-1626660797195)(img/1587539056744.png)]

Console Login

Account, password: nacos

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-opRM9jTg-1626660797196)(img/1587539128223.png)]

Console page

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-Vzw0U146-1626660797196)(img/1587539185231.png)]

Spring cloud Alibaba component

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zK0wnbY1-1626660797197)(img/1587539317677.png)]

3.6.2-Nacos quick start

nacos-provider pom.xml

<dependencies>

        <!--nacos-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.1.0</version>
        </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>
        </dependency>

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



    </dependencies>

application.yml

server:  port: 8000spring:  cloud:    nacos:      discovery:        server-addr:  127.0.0.1:8848 # to configure nacos Server address  application:    name: nacos-provider # Service name

nacos consumer pom.xml

<dependencies>

        <!--nacos-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>0.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.1.0</version>
        </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>
        </dependency>

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



    </dependencies>

application.yml

server:
  port: 9000


spring:
  cloud:
    nacos:
      discovery:
        server-addr:  127.0.0.1:8848 # Configure nacos server address
  application:
    name: nacos-consumer # Service name

Console display

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-OihxP8QD-1626660797197)(img/1587540058184.png)]

Details page

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-U7kjh3IC-1626660797198)(img/1587539884192.png)]

Sample code

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-E8u0uapi-1626660797198)(img/1587539969096.png)]

Topics: Java Spring Cloud