Crazy God SpringCloud study notes

distributed

Dubbo and zookeeper integration

What is a distributed system?

In the book "Distributed System Principles and Paradigms", there is the following definition: "A distributed system is a collection of several independent computers that appear to users as a single related system";

A distributed system is a system composed of a group of computer nodes that communicate through a network and coordinate their work to complete a common task. The emergence of distributed systems is to use cheap and ordinary machines to complete computing and storage tasks that cannot be completed by a single computer. Its purpose is to use more machines to process more data .

A distributed system is a software system built on a network.

First of all, it needs to be clear that only when the processing power of a single node cannot meet the increasing computing and storage tasks, and the hardware upgrade (adding memory, adding disk, using a better CPU) is too expensive, the application When further optimization is not possible, we need to consider distributed systems. Because the problems to be solved by the distributed system itself are the same as those of the stand-alone system, and due to the multi-node topology of the distributed system and network communication, many problems that the stand-alone system does not have will be introduced. In order to solve these problems, more problems will be introduced. Mechanisms and agreements, which bring more problems.

Dubbo

With the development of the Internet, the scale of website applications continues to expand, and the conventional vertical application architecture can no longer cope. Distributed service architecture and mobile computing architecture are imperative, and a governance system is urgently needed to ensure the orderly evolution of the architecture.

There is such a picture in Dubbo's official website document

Please add a picture description

Single Application Architecture

When the website traffic is small, only one application is needed to deploy all functions together to reduce deployment nodes and costs. At this time, the data access framework (ORM) used to simplify the workload of adding, deleting, modifying and checking is the key.

Please add a picture description

It is suitable for small websites and small management systems, and deploys all functions into one function, which is easy to use.

shortcoming

  1. Performance scaling is difficult
  2. collaborative development problem
  3. Not conducive to upgrade and maintenance

Vertical Application Architecture

When the number of visits gradually increases, the acceleration brought by the addition of machines for a single application becomes smaller and smaller, and the application is split into several independent applications to improve efficiency. At this time, the web framework (MVC) used to accelerate the development of front-end pages is the key.

Please add a picture description

The independent deployment of each module is achieved by segmenting the business, which reduces the difficulty of maintenance and deployment. It is easier to manage each team's duties, and the performance expansion is also more convenient and more targeted.

Disadvantages: Common modules cannot be reused, development waste

Distributed Service Architecture

When there are more and more vertical applications, the interaction between applications is inevitable. The core business is extracted as an independent service, and a stable service center is gradually formed, so that front-end applications can respond to changing market demands more quickly. At this time, the **Distributed Service Framework (RPC)** used to improve business reuse and integration is the key.

Please add a picture description

Mobile Computing Architecture

When there are more and more services, problems such as capacity evaluation and waste of small service resources gradually appear. At this time, it is necessary to add a scheduling center to manage the cluster capacity in real time based on access pressure and improve cluster utilization. At this time, the resource scheduling and governance center (SOA) [Service Oriented Architecture] for improving machine utilization is the key.

Please add a picture description

What is RPC

RPC [Remote Procedure Call] refers to remote procedure call, which is an inter-process communication method. It is a technical idea, not a specification. It allows a program to call a procedure or function in another address space (usually another machine on a shared network) without the programmer explicitly encoding the details of the remote call. That is to say, no matter whether the programmer calls a local or a remote function, the calling code written is essentially the same.

That is to say, there are two servers A and B. An application is deployed on server A. If it wants to call the function/method provided by the application on server B, it cannot be called directly because it is not in the same memory space. It needs to express the semantics and methods of the call through the network. Conveys the data for the call. Why use RPC? It is a requirement that cannot be fulfilled in a process, or even in a computer, through local calls, such as communication between different systems, or even communication between different organizations. Due to the horizontal expansion of computing power, it needs to be composed of multiple machines. Deploy applications on the cluster. RPC is to call remote functions like calling local functions;

Recommended reading article: https://www.jianshu.com/p/2accc2840a1b

Basic principles of RPC

Please add a picture description

Detailed steps

Please add a picture description

RPC has two core modules: communication and serialization.

Environment build

Dubbo

Apache Dubbo |ˈdʌbəʊ| is a high-performance, lightweight open source Java RPC framework, which provides three core capabilities: interface-oriented remote method invocation, intelligent fault tolerance and load balancing, and automatic service registration and discovery.

Dubbo official website http://dubbo.apache.org/zh-cn/index.html

1. Understand the characteristics of Dubbo

2. View official documents

basic concept of dubbo

Please add a picture description

Service provider (Provider): The service provider that exposes the service. When the service provider starts, it registers the service it provides with the registration center.

Service consumer (Consumer): The service consumer who calls the remote service. When the service consumer starts, it subscribes to the registration center for the service it needs. The service consumer selects from the provider address list based on the soft load balancing algorithm. One provider makes the call, and if the call fails, another provider is selected for call.

Registry : The registry returns the service provider address list to the consumer. If there is a change, the registry will push the change data to the consumer based on the long connection

Monitoring Center (Monitor): service consumers and providers, accumulative call times and call time in memory, regularly send statistical data to the monitoring center every minute

Description of calling relationship

  • The service container is responsible for starting, loading, and running the service provider.
  • When the service provider starts, it registers the services it provides with the registration center
  • When a service consumer starts, it subscribes to the registration center for the services it needs.
  • The registration center returns the service provider address list to the consumer. If there is a change, the registration center will push the change data to the consumer based on the long connection.
  • Service consumers, from the provider address list, select a provider to call based on the soft load balancing algorithm, and if the call fails, select another provider to call.
  • Service consumers and providers accumulate the number of calls and call time in memory, and regularly send statistical data to the monitoring center every minute.

Environment build

All software has been configured, inC:\Baidu Netdisk\Silicon Valley\dubbo\Courseware, Materials\Courseware\softwareCheck

zookeeper :

  • Port number: clientPort=2181
  • Directory for temporary data storage (writable relative path): dataDir=./

dubbo-admin :

  • File location:C:\Baidu Netdisk\Silicon Valley\dubbo\Courseware, Materials\Courseware\software\incubator-dubbo-ops-master\dubbo-admin

  • Run dubbo-admin:

    # zookeeper的服务一定要打开!
    java -jar dubbo-admin-0.0.1-SNAPSHOT.jar
    

After the execution is completed, let's visit http://localhost:7001/. At this time, we need to enter the login account and password. We are all default root-root;

So far, the environment has been built successfully!

SpringBoot+Dubbo+zookeeper

frame building

1. Start zookeeper!

2. IDEA creates an empty project;

3. Create a module to implement the service provider: provider-server, just select the web dependency

4. After the project is created, we write a service, such as the service of selling tickets;

write interface

package com.kuang.service;

public interface TicketService {
    
    
    String getTicket();
}

Write the implementation class

package com.kuang.service;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

@Service
@Component
public class TicketServiceImpl implements TicketService{
    
    
    @Override
    public String getTicket() {
    
    
        return "xiaotengteng learn Dubbo+zookeeper";
    }
}

5. Create a module to realize the service consumer: consumer-server, just select web dependency

6. After the project is created, we write a service, such as a user service;

write service

package com.kuang.service;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    

    //我们需要去拿注册中心的服务

}

Requirements: Now our users want to use the service of buying tickets, how to do this?

service provider

1. To register the service provider to the registration center, we need to integrate Dubbo and zookeeper, so we need to import the package

We enter github from dubbo official website, look at the help document below, find dubbo-springboot, and find the dependency package

<!-- Dubbo Spring Boot Starter -->
<dependency>
   <groupId>org.apache.dubbo</groupId>
   <artifactId>dubbo-spring-boot-starter</artifactId>
   <version>2.7.3</version>
</dependency>    

Let's go to the maven warehouse to download the zookeeper package, zkclient;

<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
   <groupId>com.github.sgroschupf</groupId>
   <artifactId>zkclient</artifactId>
   <version>0.1</version>
</dependency>

[The pit of the new version] zookeeper and its dependent packages, to resolve log conflicts, log dependencies need to be removed;

<!-- 引入zookeeper -->
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-framework</artifactId>
   <version>2.12.0</version>
</dependency>
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-recipes</artifactId>
   <version>2.12.0</version>
</dependency>
<dependency>
   <groupId>org.apache.zookeeper</groupId>
   <artifactId>zookeeper</artifactId>
   <version>3.4.14</version>
   <!--排除这个slf4j-log4j12-->
   <exclusions>
       <exclusion>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
       </exclusion>
   </exclusions>
</dependency>

2. Configure dubbo related properties in the springboot configuration file!

#当前应用名字
dubbo.application.name=provider-server
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181
#扫描指定包下服务
dubbo.scan.base-packages=com.kuang.service

3. Configure service annotations in the service implementation class and publish the service!Pay attention to the package problem

package com.kuang.service;

import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;

@Service
@Component
public class TicketServiceImpl implements TicketService{
    
    
    @Override
    public String getTicket() {
    
    
        return "xiaotengteng learn Dubbo+zookeeper";
    }
}

Logical understanding: when the application is started, dubbo will scan the service with @component annotation under the specified package and publish it in the specified registry!

service consumer

1. Import dependencies, which are the same as the previous dependencies;

<!--dubbo-->
<!-- Dubbo Spring Boot Starter -->
<dependency>
   <groupId>org.apache.dubbo</groupId>
   <artifactId>dubbo-spring-boot-starter</artifactId>
   <version>2.7.3</version>
</dependency>
<!--zookeeper-->
<!-- https://mvnrepository.com/artifact/com.github.sgroschupf/zkclient -->
<dependency>
   <groupId>com.github.sgroschupf</groupId>
   <artifactId>zkclient</artifactId>
   <version>0.1</version>
</dependency>
<!-- 引入zookeeper -->
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-framework</artifactId>
   <version>2.12.0</version>
</dependency>
<dependency>
   <groupId>org.apache.curator</groupId>
   <artifactId>curator-recipes</artifactId>
   <version>2.12.0</version>
</dependency>
<dependency>
   <groupId>org.apache.zookeeper</groupId>
   <artifactId>zookeeper</artifactId>
   <version>3.4.14</version>
   <!--排除这个slf4j-log4j12-->
   <exclusions>
       <exclusion>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-log4j12</artifactId>
       </exclusion>
   </exclusions>
</dependency>

2. Configuration parameters

#当前应用名字
dubbo.application.name=consumer-server
#注册中心地址
dubbo.registry.address=zookeeper://127.0.0.1:2181

3. Originally, the normal procedure is to package the interface of the service provider and then import it with a pom file. Here we use a simple method to directly take the interface of the service. The path must be correct, that is, the same as the service provider;

# 将服务提供者 TicketService 复制到 服务消费者 相同路径下

4. Improve consumer services

package com.kuang.service;

import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    
    

    @Reference
    TicketService ticketService;

    public void buyTicket(){
    
    
        String ticket = ticketService.getTicket();
        System.out.println("在注册中心买到:"+ticket);
    }

}

5. Writing test classes;

package com.kuang;

import com.kuang.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class ConsumerServerApplicationTests {
    
    

    @Autowired
    UserService userService;

    @Test
    void contextLoads(){
    
    
        userService.buyTicket();
    }
}

start test

1. Open zookeeper

2. Open dubbo-admin to monitor [you don’t need to do it]

3. Start the server

4. Consumer consumption test, the result:

# 在注册中心买到:xiaotengteng learn Dubbo+zookeeper(idea控制台输出)

monitoring Center:

Both service provider and consumer can see records

Notice:

  • Both the service provider and the consumer need to be turned on at the same time. At the beginning, only the provider was turned on. Although the consumer can buy tickets, the dubbo monitoring center cannot see the consumer record. It is no problem to start the consumer test after both are turned on.

ok, this is the application of SpingBoot + dubbo + zookeeper to realize distributed development, which is actually an idea of ​​service splitting;

microservice

foreword

1.1 Study Advice

  • Proficiency in rapid development of springboot microservices
  • Understand Dubbo+zookeeper distributed foundation

1.2 Article Outline

Five components of SpringCloud:

  • Service Registration and Discovery - Netflix Eureka

  • load balancing:

    • Client Load Balancing - Netflix Ribbon
    • Server-side load balancing - Feign (it also depends on Ribbon, just change the calling method RestTemplete to Service interface)
  • Circuit Breaker - Netflix Hystrix

  • Service Gateway - Netflix Zuul

  • Distributed configuration - Spring Cloud Config

1.3 Common Interview Questions

  1. What are microservices?

  2. How do microservices communicate independently?

  3. What are the differences between Spring Cloud and Dubbo?

  4. Spring Cloud and Dubbo, please talk about your understanding of them

  5. What is a service circuit breaker? What is service degradation?

  6. What are the pros and cons of microservices? Tell me about the pitfalls you encountered in project development

  7. What microservice technology stacks do you know? List one or two

  8. Both Eureka and zookeeper can provide service registration and discovery, please talk about the difference between the two

    ……

Microservices overview

2.1 What are microservices?

What are microservices

Microservice (Microservice Architecture) is an architectural idea that has become popular in recent years, and it is difficult to sum up its concept in one word.

What exactly are microservices? Here we quote Martin Fowler, Chief Scientist at ThoughtWorks, in 2014:

Original article: https://martinfowler.com/articles/microservices.html

Sinicization: https://www.cnblogs.com/liuning8023/p/4493156.html

  • For now, the industry does not have a unified, standard definition for microservices.
  • But generally speaking, the microservice architecture is an architectural pattern, or an architectural style, which divides a single application into a set of small services , and each service runs in its own independent process. Services coordinate with each other and configure each other to provide users with ultimate value. Services communicate with each other using a lightweight communication mechanism ( HTTP ). Each service is built around a specific business and can be deployed independently In the production environment, in addition, a unified and centralized service management mechanism should be avoided as far as possible. For a specific service, an appropriate language should be selected according to the business context, and the tool (Maven) should be used to build it. There can be a Very lightweight centralized management to coordinate these services, services can be written in different languages ​​or use different data stores.

Then understand it from a technical perspective

  • The core of micro-service is to split the traditional one-stop application into services one by one according to the business, and completely decouple them. Each micro-service provides a single business function service, and one service does one thing. From a technical point of view Watching is a small and independent processing process, similar to the concept of a process, which can be started or destroyed independently, and has its own independent database.

2.2 Microservice and Microservice Architecture

microservice

​ The emphasis is on the size of the service. It focuses on a certain point. It is a service application that specifically solves a certain problem/provides landing corresponding services. In a narrow sense, it can be regarded as a microservice project in IDEA, or Moudel. The IDEA tool uses independent small Moudel developed by Maven. It is specifically a small module developed by SpringBoot. Professional tasks are handed over to professional modules, and one module does one thing. Emphasis is on each individual, each individual to complete a specific task or function.

microservice architecture

A new architectural form, proposed by Martin Fowler in 2014.

Microservice architecture is an architectural pattern, which divides a single application program into a group of small services, and the services coordinate and cooperate with each other to provide users with ultimate value. Each service runs in its own independent process, and services use lightweight communication mechanisms (such as HTTP) to cooperate with each other. Each service is built around a specific business and can be independently deployed to production environment, in addition, a unified and centralized service management mechanism should be avoided as much as possible. For a specific service, an appropriate language and tool (such as Maven) should be selected to build it according to the business context .

2.3 Advantages and disadvantages of microservices

advantage

  • Single Responsibility Principle;
  • Each service is cohesive enough, small enough, and the code is easy to understand, so that it can focus on a specified business function or business requirement;
  • The development is simple and the development efficiency is high. A service may be dedicated to only one thing;
  • Microservices can be developed independently by a small team, which only needs 2-5 developers;
  • Microservices are loosely coupled and functionally meaningful services that are independent in both the development and deployment phases;
  • Microservices can be developed in different languages;
  • Easy to integrate with third parties, microservices allow easy and flexible integration of automatic deployment, through continuous integration tools, such as jenkins, Hudson, bamboo;
  • Microservices are easy to be understood, modified and maintained by a developer, so that small teams can pay more attention to their own work results, and can reflect value without cooperation;
  • Microservices allow the utilization and integration of the latest technologies;
  • Microservices are just business logic code, not mixed with HTML, CSS, or other interfaces;
  • Each microservice has its own storage capacity, and can have its own database or a unified database;

shortcoming

  • Developers deal with the complexities of distributed systems;
  • Multi-service operation and maintenance is difficult. With the increase of services, the pressure of operation and maintenance is also increasing;
  • System deployment dependency issues;
  • Inter-service communication cost issues;
  • Data consistency issues;
  • System integration testing issues;
  • performance and monitoring issues;

2.4 What are the microservice technology stacks?

Microservice technology entry Floor technology
service development SpringBoot、Spring、SpringMVC等
Service configuration and management Archaius from Netflix, Diamond from Ali, etc.
Service Registration and Discovery Eureka、Consul、Zookeeper等
service call Rest、PRC、gRPC
service fuse Hystrix、Envoy等
load balancing Ribbon, Nginx, etc.
Service interface call (simplified tool for clients to call services) Fegin et al.
message queue Kafka, RabbitMQ, ActiveMQ, etc.
Service configuration center management SpringCloudConfig、Chef等
Service Routing (API Gateway) Zuul et al.
service monitoring Zabbix、Nagios、Metrics、Specatator等
full link tracking Zipkin、Brave、Dapper等
Dataflow Operations Development Kit SpringCloud Stream (encapsulates and sends and receives messages with Redis, Rabbit, Kafka, etc.)
total time message stack SpringCloud Bus
service deployment Docker、OpenStack、Kubernetes等

2.5 Why choose Spring Cloud as the microservice architecture

  1. Selection basis

    • Overall solution and framework maturity
    • Community popularity
    • maintainability
    • learning curve
  2. What are the current microservice architectures of major IT companies?

    • Ali: dubbo+HFS
    • Jingdong: JFS
    • Sina: Motan
    • Dangdang: DubboX
  3. Comparison of Microservice Frameworks

Function Point/Service Framework Netflix/SpringCloud look gRPC Thrit Hammer / HammerX
Functional positioning Complete microservice framework RPC framework, but integrates ZK or Consul to realize basic service registration discovery in cluster environment RPC framework RPC framework service framework
Support Rest Yes, Ribbon supports a variety of pluggable serial number options no no no no
Support RPC no Yes (Hession2) yes yes yes
Support multiple languages Yes (Rest form) no yes yes no
load balancing Yes (server-side zuul+client-side Ribbon), zuul-service, dynamic routing, cloud load balancing Eureka (for middle-tier servers) yes (client) no no yes (client)
configuration service Netfix Archaius, Spring Cloud Config Server centralized configuration Yes (provided by Zookeeper) no no no
Service call chain monitoring Yes (zuul), zuul provides edge services, API gateway no no no no
High availability/fault tolerance Yes (server-side Hystrix + client-side Ribbon) yes (client) no no yes (client)
Typical application case Netflix Theirs Google Facebook
Community activity high generally high generally Maintenance resumed after 2017, after a 5-year hiatus
learning difficulty medium Low high high Low
Documentation richness high generally generally generally high
other Spring Cloud Bus为我们的应用程序带来了更多管理端点 支持降级 Netflix内部在开发集成gRPC IDL定义 实践的公司比较多

Spring Cloud 入门概述

3.1 Spring Cloud 是什么?

Spring官网:https://spring.io/

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-eDPloR33-1674724143825)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\cloud-diagram-1a4cad7294b4452864b5ff57175dd983.svg)]

3.2 Spring Cloud 和 SpringBoot 的关系

  • SpringBoot专注于开发方便的开发单个个体微服务;
  • SpringCloud是关注全局的微服务协调整理治理框架,它将SpringBoot开发的一个个单体微服务,整合并管理起来,为各个微服务之间提供:配置管理、服务发现、断路器、路由、为代理、事件总栈、全局锁、决策竞选、分布式会话等等集成服务;
  • SpringBoot可以离开SpringCloud独立使用,开发项目,但SpringCloud离不开SpringBoot,属于依赖关系;
  • SpringBoot专注于快速、方便的开发单个个体微服务,SpringCloud关注全局的服务治理框架;

3.3 Dubbo 和 Spring Cloud 技术选型

分布式+服务治理 Dubbo

目前成熟的互联网架构,应用服务化拆分 + 消息中间件

Dubbo 和 Spring Cloud 对比

可以看一下社区活跃度:

https://github.com/dubbo

https://github.com/spring-cloud

对比结果:

Dubbo SpringCloud
服务注册中心 Zookeeper Spring Cloud Netfilx Eureka
服务调用方式 RPC REST API
服务监控 Dubbo-monitor Spring Boot Admin
断路器 不完善 Spring Cloud Netfilx Hystrix
服务网关 Spring Cloud Netfilx Zuul
分布式配置 Spring Cloud Config
服务跟踪 Spring Cloud Sleuth
消息总栈 Spring Cloud Bus
数据流 Spring Cloud Stream

最大区别:Spring Cloud 抛弃了Dubbo的RPC通信,采用的是基于HTTP的REST方式

严格来说,这两种方式各有优劣。虽然从一定程度上来说,后者牺牲了服务调用的性能,但也避免了上面提到的原生RPC带来的问题。而且REST相比RPC更为灵活,服务提供方和调用方的依赖只依靠一纸契约,不存在代码级别的强依赖,这个优点在当下强调快速演化的微服务环境下,显得更加合适。

品牌机和组装机的区别

社区支持与更新力度的区别

**总结:**二者解决的问题域不一样:Dubbo的定位是一款RPC框架,而SpringCloud的目标是微服务架构下的一站式解决方案。

3.4 Spring cloud 能干嘛?

  • Distributed/versioned configuration 分布式/版本控制配置
  • Service registration and discovery 服务注册与发现
  • Routing 路由
  • Service-to-service calls 服务到服务的调用
  • Load balancing 负载均衡配置
  • Circuit Breakers 断路器
  • Distributed messaging 分布式消息管理

3.5 Spring Cloud 下载

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C6PegjnI-1674724143825)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673007630810.png)]

SpringCloud没有采用数字编号的方式命名版本号,而是采用了伦敦地铁站的名称,同时根据字母表的顺序来对应版本时间顺序,比如最早的Realse版本:Angel,第二个Realse版本:Brixton,然后是Camden、Dalston、Edgware,目前最新的是2022.0.0 CURRENT GA通用稳定版。

自学参考书:

Spring Cloud Rest 学习环境搭建

4.1 概述

  • 我们会使用一个Dept部门模块做一个微服务通用案例Consumer消费者(Client)通过REST调用Provider提供者(Server)提供的服务。
  • 回顾Spring,SpringMVC,Mybatis等以往学习的知识。
  • Maven的分包分模块架构复习。

一个简单的Maven模块结构是这样的:
– app-parent: 一个父项目(app-parent)聚合了很多子项目(app-util\app-dao\app-web…)
|-- pom.xml
|
|-- app-core
||---- pom.xml
|
|-- app-web
||---- pom.xml

一个父工程带着多个Moudule子模块

SpringCloud:父工程

  • springcloud-api:【封装的整体entity/接口/公共配置等】
  • springcloud-consumer-dept-80:【服务提供者】
  • springcloud-provider-dept-9000:【服务消费者】

4.2 创建父工程

  • 新建父工程项目springcloud,切记Packageing是pom模式
  • 主要是定义POM文件,将后续各个子模块公用的jar包等统一提取出来,类似一个抽象父类

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SpringCloud</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>springcloud-api</module>
        <module>springcloud-provider-dept-9000</module>
        <module>springcloud-consumer-dept-80</module>
    </modules>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <junit.version>4.12</junit.version>
        <log4j.version>1.2.17</log4j.version>
        <lombok.version>1.18.24</lombok.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <!--springCloud的依赖-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Greenwich.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--SpringBoot-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.6.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <!--数据库-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.25</version>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.2.14</version>
            </dependency>
            <!--SpringBoot 启动器-->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>2.2.2</version>
            </dependency>
            <!--日志测试~-->
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>1.2.3</version>
            </dependency>
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>${junit.version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>${log4j.version}</version>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

springcloud-provider-dept-8001的dao接口调用springcloud-api模块下的pojo,可使用在springcloud-provider-dept-8001的pom文件导入springcloud-api模块依赖的方式:

<!--我们需要拿到实体类,所以需要配置api module-->
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

项目详见:C:\Users\戴尔\IdeaProjects\kuang\SpringCloud

Eureka 服务注册中心

5.1 什么是Eureka

  • Netflix在涉及Eureka时,遵循的就是API原则.
  • Eureka是Netflix的有个子模块,也是核心模块之一。Eureka是基于REST的服务,用于定位服务,以实现云端中间件层服务发现和故障转移,服务注册与发现对于微服务来说是非常重要的,有了服务注册与发现,只需要使用服务的标识符,就可以访问到服务,而不需要修改服务调用的配置文件了,功能类似于Dubbo的注册中心,比如Zookeeper.

5.2 原理解释

  • Eureka 基本架构
    • Springcloud 封装了Netflix公司开发的Eureka模块来实现服务注册与发现 (对比Zookeeper).
    • Eureka采用了C-S的架构设计,EurekaServer作为服务注册功能的服务器,他是服务注册中心.
    • 而系统中的其他微服务,使用Eureka的客户端连接到EurekaServer并维持心跳连接。这样系统的维护人员就可以通过EurekaServer来监控系统中各个微服务是否正常运行,Springcloud 的一些其他模块 (比如Zuul) 就可以通过EurekaServer来发现系统中的其他微服务,并执行相关的逻辑.

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-L93q21Cq-1674724143826)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20200521130157770.png)]

  • Dubbo 架构对比

Please add a picture description

  • Eureka 包含两个组件:Eureka ServerEureka Client.

  • Eureka Server 提供服务注册,各个节点启动后,回在EurekaServer中进行注册,这样Eureka Server中的服务注册表中将会储存所有课用服务节点的信息,服务节点的信息可以在界面中直观的看到.

  • Eureka Client 是一个Java客户端,用于简化EurekaServer的交互,客户端同时也具备一个内置的,使用轮询负载算法的负载均衡器。在应用启动后,将会向EurekaServer发送心跳 (默认周期为30秒) 。如果Eureka Server在多个心跳周期内没有接收到某个节点的心跳,EurekaServer将会从服务注册表中把这个服务节点移除掉 (默认周期为90s).

  • 三大角色

    • Eureka Server :提供服务注册与发现
    • Service Provider:服务生产方,将自身服务注册到Eureka中,从而是服务消费方能够找到
    • Service Consumer:服务消费方,从Eureka中获取到注册服务列表,从而找到消费服务

5.3 构建步骤

eureka-server

  1. springcloud-eureka-7001 模块建立

  2. pom.xml 配置

    <!--导包~-->
    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
        <!--导入Eureka Server依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--热部署工具-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
    
  3. application.yml

       server:
         port: 7001
       # Eureka配置
       eureka:
         instance:
           # Eureka服务端的实例名字
           hostname: 127.0.0.1
         client:
           # 表示是否向 Eureka 注册中心注册自己(这个模块本身是服务器,所以不需要)
           register-with-eureka: false
           # fetch-registry如果为false,则表示自己为注册中心,客户端的化为 ture
           fetch-registry: false
           # Eureka监控页面~
           service-url:
             defaultZone: http://${
          
          
             eureka.instance.hostname}:${
          
          
             server.port}/eureka/
    

    源码中Eureka 的默认配置(Ctrl+左键点击service-url 查看)

Please add a picture description

  1. 主启动类

    package com.kuang.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
    
    @SpringBootApplication
    @EnableEurekaServer
    //@EnableEurekaServer  服务端的启动类,可以接受别人注册进来
    public class EurekaServer_7001 {
          
          
        public static void main(String[] args) {
          
          
    
            SpringApplication.run(EurekaServer_7001.class,args);
        }
    }
    
  2. 启动成功后访问 http://localhost:7001/ 得到以下页面

Please add a picture description

eureka-client

调整之前创建的 springcloud-provider-dept-9000

  1. 添加eureka依赖

    <!--Eureka依赖-->
    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    
  2. application.yml 新增eureka

    # Eureka配置:配置服务注册中心地址
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:7001/eureka/
    
  3. 为主启动类添加@EnableEurekaClient注解

    package com.kuang.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    
    @SpringBootApplication
    @EnableEurekaClient
    //@EnableEurekaClient 开启Eureka 客户端注解 在服务启动后自动向注册中心注册服务
    public class springcloud_provider_dept {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(springcloud_provider_dept.class,args);
        }
    }
    
    
  4. 先启动7001服务端后启动8001客户端进行测试,然后访问监控页http://localhost:7001/ 产看结果如图,成功

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oqAOv1ZO-1674724143826)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673180930517.png)]

修改eureka上默认配置信息

# Eureka配置:配置服务注册中心地址
eureka:
  client:
    service-url:
      defaultZone: http://localhost:7001/eureka/
  instance:
    instance-id: springcloud-provider-dept-9000 #修改Eureka上的默认描述信息
  • 结果如图:

  • 如果此时停掉springcloud-provider-dept-9000等30s后 监控会开启保护机制:[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hmGhjZrc-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673180930517.png)]

配置关于服务加载的监控信息

  • pom.xml

    <!--actuator完善监控信息-->
    <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    
  • application.yml

    # Eureka 配置:配置服务注册中心地址
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:7001/eureka/
      # 修改eureka上的默认描述信息
      instance:
        instance-id: springcloud-provider-dept-9000
    info:
      app.name: kuang-springcloud
      company.name: 河南师范大学
    
  • 此时刷新监控页面,点击 springcloud-provider-dept-9000进入页面显示

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IMP7gDcD-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673181921577.png)]

3. Eureka 自我保护机制:好死不如赖活着

一句话总结就是:某时刻某一个微服务不可用,eureka不会立即清理,依旧会对该微服务的信息进行保存!

  • 默认情况下,当eureka server在一定时间内没有收到实例的心跳,便会把该实例从注册表中删除(默认是90秒),但是,如果短时间内丢失大量的实例心跳,便会触发eureka server的自我保护机制,比如在开发测试时,需要频繁地重启微服务实例,但是我们很少会把eureka server一起重启(因为在开发过程中不会修改eureka注册中心),当一分钟内收到的心跳数大量减少时,会触发该保护机制。可以在eureka管理界面看到Renews threshold和Renews(last min),当后者(最后一分钟收到的心跳数)小于前者(心跳阈值)的时候,触发保护机制,会出现红色的警告:EMERGENCY!EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY'RE NOT.RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEGING EXPIRED JUST TO BE SAFE.从警告中可以看到,eureka认为虽然收不到实例的心跳,但它认为实例还是健康的,eureka会保护这些实例,不会把它们从注册表中删掉。
  • 该保护机制的目的是避免网络连接故障,在发生网络故障时,微服务和注册中心之间无法正常通信,但服务本身是健康的,不应该注销该服务,如果eureka因网络故障而把微服务误删了,那即使网络恢复了,该微服务也不会重新注册到eureka server了,因为只有在微服务启动的时候才会发起注册请求,后面只会发送心跳和服务列表请求,这样的话,该实例虽然是运行着,但永远不会被其它服务所感知。所以,eureka server在短时间内丢失过多的客户端心跳时,会进入自我保护模式,该模式下,eureka会保护注册表中的信息,不在注销任何微服务,当网络故障恢复后,eureka会自动退出保护模式。自我保护模式可以让集群更加健壮。
  • 但是我们在开发测试阶段,需要频繁地重启发布,如果触发了保护机制,则旧的服务实例没有被删除,这时请求有可能跑到旧的实例中,而该实例已经关闭了,这就导致请求错误,影响开发测试。所以,在开发测试阶段,我们可以把自我保护模式关闭,只需在eureka server配置文件中加上如下配置即可:eureka.server.enable-self-preservation=false【不推荐关闭自我保护机制】

详细内容可以参考下这篇博客内容:https://blog.csdn.net/wudiyong22/article/details/80827594

4. 注册进来的服务,获取一些消息(团队开发会用到)

DeptController.java新增方法

/**
 * DiscoveryClient 可以用来获取一些配置的信息,得到具体的微服务!
 */
@Autowired
private DiscoveryClient client;
/**
 * 获取一些注册进来的微服务的信息~,
 *
 * @return
 */
@GetMapping("/dept/discovery")
public Object discovery() {
    
    
    // 获取微服务列表的清单
    List<String> services = client.getServices();
    System.out.println("discovery=>services:" + services);
    // 得到一个具体的微服务信息,通过具体的微服务id,applicaioinName;
    List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
    for (ServiceInstance instance : instances) {
    
    
        System.out.println(
                instance.getHost() + "\t" + // 主机名称
                        instance.getPort() + "\t" + // 端口号
                        instance.getUri() + "\t" + // uri
                        instance.getServiceId() // 服务id
        );
    }
    return this.client;
}

主启动类中加入@EnableDiscoveryClient 注解

@SpringBootApplication
// @EnableEurekaClient 开启Eureka客户端注解,在服务启动后自动向注册中心注册服务
@EnableEurekaClient
// @EnableEurekaClient 开启服务发现客户端的注解,可以用来获取一些配置的信息,得到具体的微服务
@EnableDiscoveryClient
public class DeptProvider_8001 {
    
    
    ...
}

结果如图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZiFZZfxO-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673183739648.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-S0junuSD-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673183791214.png)]

5.4 集群环境配置

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-NYL82fMh-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20201120102037473.png)]

初始化

新建springcloud-eureka-7002、springcloud-eureka-7003 模块

1.为pom.xml添加依赖 (与springcloud-eureka-7001相同)

<!--导包~-->
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-eureka-server -->
    <!--导入Eureka Server依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-eureka-server</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    <!--热部署工具-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
</dependencies>

2.application.yml配置(与springcloud-eureka-7001相同)

server:
  port: 7003
# Eureka配置
eureka:
  instance:
    hostname: localhost # Eureka服务端的实例名字
  client:
    register-with-eureka: false # 表示是否向 Eureka 注册中心注册自己(这个模块本身是服务器,所以不需要)
    fetch-registry: false # fetch-registry如果为false,则表示自己为注册中心
    service-url: # 监控页面~
      # 重写Eureka的默认端口以及访问路径 --->http://localhost:7001/eureka/
      defaultZone: http://${
    
    
    eureka.instance.hostname}:${
    
    
    server.port}/eureka/

3.主启动类(与springcloud-eureka-7001相同,不再重复)

4.集群成员相互关联

#在hosts文件最后加上,要访问的本机名称,默认是localhost
127.0.0.1 eureka7001.com
127.0.0.1 eureka7002.com
127.0.0.1 eureka7003.com

5.修改application.yml,在集群中使springcloud-eureka-7001关联springcloud-eureka-7002、springcloud-eureka-7003

完整的springcloud-eureka-7001下的application.yml如下

server:
  port: 7001

eureka:
  instance:
    # Eureka 服务端实例名字
    hostname: eureka7001.com
  client:
    # 表示是否向 Eureka 注册中心注册自己 (这个模块本身就是服务器,)
    register-with-eureka: false
    # fetch-registry 如果为FALSE 表示自己为注册中心,客户端的为 TRUE
    fetch-registry: false
    # Eureka 监控页面
    service-url:
      defaultZone: http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

springcloud-eureka-7002、springcloud-eureka-7003 配置同理

6.修改 springcloud-provider-dept-9000 的application.yml

  • 修改Eureka配置:配置服务注册中心地址

    # Eureka 配置:配置服务注册中心地址
    eureka:
      client:
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
      # 修改eureka上的默认描述信息
      instance:
        instance-id: springcloud-provider-dept-9000
    info:
      app.name: kuang-springcloud
      company.name: 河南师范大学
    

    这样模拟集群就搭建号了,就可以把一个项目挂载到三个服务器上了

7.启动项目,运行结果如下:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-EmqGwbB6-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673187777429.png)]

5.5 对比 zookeeper

回顾CAP原则

  • RDBMS(MYSQL\ORACLE\SQLServer)===>ACID
  • NoSQL(Redis\MongoDB)===>CAP

ACID 是什么?

  • A(Atomicity)原子性
  • C(Consistency)一致性
  • I(Isolation)隔离性
  • D(Durability)持久性

CAP 是什么?

  • C(Consistency)强一致性
  • A(Avaliability)可用性
  • P(Partition tolerance)分区容错性

CAP的三进二:CA、AP、CP

CAP 理论的核心

  • 一个分布式系统不可能同时很好的满足一致性,可用性和分区容错性这三个需求
  • 根据CAP原理,将NoSQL数据库分成了满足CA原则,满足CP原则和满足AP原则三大类
    • CA:单点集群,满足一致性,可用性的系统,通常可扩展性较差
    • CP:满足一致性,分区容错的系统,通常性能不是特别高
    • AP:满足可用性,分区容错的系统,通常可能对一致性要求低一些

作为分布式服务注册中心,Eureka比Zookeeper好在哪里?

著名的CAP理论指出,一个分布式系统不可能同时满足C (一致性) 、A (可用性) 、P (容错性),由于分区容错性P在分布式系统中是必须要保证的,因此我们只能再A和C之间进行权衡。

  • Zookeeper 保证的是 CP —> 满足一致性,分区容错的系统,通常性能不是特别高
  • Eureka 保证的是 AP —> 满足可用性,分区容错的系统,通常可能对一致性要求低一些

Zookeeper保证的是CP

  • 当向注册中心查询服务列表时,我们可以容忍注册中心返回的是几分钟以前的注册信息,但不能接收服务直接down掉不可用。也就是说,服务注册功能对可用性的要求要高于一致性。但zookeeper会出现这样一种情况,当master节点因为网络故障与其他节点失去联系时,剩余节点会重新进行leader选举。问题在于,选举leader的时间太长,30-120s,且选举期间整个zookeeper集群是不可用的,这就导致在选举期间注册服务瘫痪。在云部署的环境下,因为网络问题使得zookeeper集群失去master节点是较大概率发生的事件,虽然服务最终能够恢复,但是,漫长的选举时间导致注册长期不可用,是不可容忍的。

Eureka保证的是AP

  • Eureka看明白了这一点,因此在设计时就优先保证可用性。Eureka各个节点都是平等的,几个节点挂掉不会影响正常节点的工作,剩余的节点依然可以提供注册和查询服务。而Eureka的客户端在向某个Eureka注册时,如果发现连接失败,则会自动切换至其他节点,只要有一台Eureka还在,就能保住注册服务的可用性,只不过查到的信息可能不是最新的,除此之外,Eureka还有之中自我保护机制,如果在15分钟内超过85%的节点都没有正常的心跳,那么Eureka就认为客户端与注册中心出现了网络故障,此时会出现以下几种情况:

    • Eureka不在从注册列表中移除因为长时间没收到心跳而应该过期的服务
    • Eureka仍然能够接受新服务的注册和查询请求,但是不会被同步到其他节点上 (即保证当前节点依然可用)
    • 当网络稳定时,当前实例新的注册信息会被同步到其他节点中

    因此,Eureka可以很好的应对因网络故障导致部分节点失去联系的情况,而不会像zookeeper那样使整个注册服务瘫痪

Ribbon:负载均衡(基于客户端)

6.1 负载均衡以及 Ribbon

Ribbon 是什么?

  • Spring Cloud Ribbon 是基于Netflix Ribbon 实现的一套客户端负载均衡的工具
  • 简单的说,Ribbon 是 Netflix 发布的开源项目,主要功能是提供客户端的软件负载均衡算法,将 Netflix 的中间层服务连接在一起。Ribbon 的客户端组件提供一系列完整的配置项,如:连接超时、重试等。简单的说,就是在配置文件中列出 LoadBalancer (简称LB:负载均衡) 后面所有的及其,Ribbon 会自动的帮助你基于某种规则 (如简单轮询,随机连接等等) 去连接这些机器。我们也容易使用 Ribbon 实现自定义的负载均衡算法!

Ribbon 能干嘛?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CqZ9rY4G-1674724143827)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20201121103107791.png)]

  • LB,即负载均衡 (LoadBalancer) ,在微服务或分布式集群中经常用的一种应用。
  • 负载均衡简单的说就是将用户的请求平摊的分配到多个服务上,从而达到系统的HA (高用)。
  • 常见的负载均衡软件有 Nginx、Lvs 等等。
  • Dubbo、SpringCloud 中均给我们提供了负载均衡,SpringCloud 的负载均衡算法可以自定义
  • 负载均衡简单分类:
    • 集中式LB
      • 即在服务的提供方和消费方之间使用独立的LB设施,如Nginx(反向代理服务器),由该设施负责把访问请求通过某种策略转发至服务的提供方!
    • 进程式 LB
      • 将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选出一个合适的服务器。
      • Ribbon 就属于进程内LB,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址!

6.2 集成 Ribbon

springcloud-consumer-dept-80向pom.xml中添加Ribbon和Eureka依赖

<!--Ribbon-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-ribbon</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>
<!--Eureka: Ribbon需要从Eureka服务中心获取要拿什么-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-eureka</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

在application.yml文件中配置Eureka

#Eureka 配置
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

主启动类上加@EnableEurekaClient注解,开启Eureka

package com.kuang.springcloud;

import com.kuang.myrule.KuangRule;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;

//Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号
@SpringBootApplication
@EnableEurekaClient //开启eureka客户端
public class springcloud_consumer_dept {
    
    

    public static void main(String[] args) {
    
    

        SpringApplication.run(springcloud_consumer_dept.class,args);
    }
}

自定义Spring配置类:ConfigBean.java 配置负载均衡实现RestTemplate

package com.kuang.springcloud.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RetryRule;
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;

@Configuration
public class ConfigBean {
    
    

    //@Configuration -- spring  applicationContext.xml
    //配置负载均衡实现RestTemplate
    // IRule
    // RoundRobinRule 轮询
    // RandomRule 随机
    // AvailabilityFilteringRule : 会先过滤掉,跳闸,访问故障的服务~,对剩下的进行轮询~
    // RetryRule : 会先按照轮询获取服务~,如果服务获取失败,则会在指定的时间内进行,重试
//    @Bean
//    public IRule myRule(){
    
    
//        return new RetryRule();
//        //return new RandomRule();//使用随机策略
//        //return new RoundRobinRule();//使用轮询策略
//        //return new AvailabilityFilteringRule();//使用轮询策略
//        //return new RetryRule();//使用轮询策略
//    }
    @Bean
    @LoadBalanced//配置负载均衡实现 RestTemplate
    public RestTemplate getRestTemplate(){
    
    
        return new RestTemplate();
    }


}

修改conroller:DeptConsumerController.java

/**
     * 服务提供方地址前缀
     * Ribbon:我们这里的地址,应该是一个变量,通过服务名来访问
     */
    //private static final String REST_URL_PREFIX="http://localhost:9000";
    //Ribbon 我们这里的地址,应该是一个变量,通过服务名来访问
    private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT-9000";

6.3 使用Ribbon实现负载均衡

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RIedZOew-1674724143828)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20200521131315626.png)]

  1. 新建两个服务提供者:springcloud-provider-dept-9001、springcloud-provider-dept-9002

  2. 参照springcloud-provider-dept-9000依次为另外两个Moudle添加pom.xml依赖 、resourece下的mybatis和application.yml配置,Java代码

  3. 启动所有服务测试,访问 http://eureka7001.com:7001 查看结果(测试通过,可以看到三个服务提供者)

  4. 访问 http://localhost/consumer/dept/selectAll ,经过多次测试发现是 轮询算法,springcloud

    可以切换和自定义负载均衡算法

切换自定义规则

在springcloud-provider-dept-80模块下的ConfigBean中进行配置,切换使用不同的规则

@Configuration
public class ConfigBean {
    
    
    //@Configuration -- spring  applicationContext.xml
    /**
     * IRule:
     * RoundRobinRule 轮询策略
     * RandomRule 随机策略
     * AvailabilityFilteringRule : 会先过滤掉,跳闸,访问故障的服务~,对剩下的进行轮询~
     * RetryRule : 会先按照轮询获取服务~,如果服务获取失败,则会在指定的时间内进行,重试
     */
    @Bean
    public IRule myRule() {
    
    
        return new RandomRule();//使用随机策略
        //return new RoundRobinRule();//使用轮询策略
        //return new AvailabilityFilteringRule();//使用轮询策略
        //return new RetryRule();//使用轮询策略
    }
}

自定义规则:

在myRule包下自定义一个配置类KuangRule.java,注意:该包不要和主启动类所在的包同级,要跟启动类所在包同级

  • KuangRule.java

    package com.kuang.myrule;
    
    import com.netflix.loadbalancer.IRule;
    import com.netflix.loadbalancer.RetryRule;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    @Configuration
    public class KuangRule {
          
          
    
        @Bean
        public IRule myRule(){
          
          
            //return new RetryRule(); 使用已有的轮转
            return new MyRandomRule();
        }
    }
    
  • 主启动类开启负载均衡并指定自定义的KuangRule配置类

    package com.kuang.springcloud;
    
    import com.kuang.myrule.KuangRule;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
    import org.springframework.cloud.netflix.ribbon.RibbonClient;
    
    //Ribbon 和 Eureka 整合以后,客户端可以直接调用,不用关心IP地址和端口号
    @SpringBootApplication
    @EnableEurekaClient //开启eureka客户端
    //开启负载均衡,并指定自定义规则
    @RibbonClient(name = "SPRINGCLOUD-PROVIDER-DEPT-9000",configuration = KuangRule.class)
    public class springcloud_consumer_dept {
          
          
    
        public static void main(String[] args) {
          
          
    
            SpringApplication.run(springcloud_consumer_dept.class,args);
        }
    }
    
    
  • 自定义负载均衡算法

    package com.kuang.myrule;
    
    import com.netflix.client.config.IClientConfig;
    import com.netflix.loadbalancer.AbstractLoadBalancerRule;
    import com.netflix.loadbalancer.ILoadBalancer;
    import com.netflix.loadbalancer.Server;
    
    import java.util.List;
    import java.util.concurrent.ThreadLocalRandom;
    
    public class MyRandomRule extends AbstractLoadBalancerRule {
          
          
    
        //参考 IRule实现类 RandomRule
    
        private int total = 5;
        private int currentIndex = 0;
        //@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE")
        public Server choose(ILoadBalancer lb, Object key) {
          
          
            if (lb == null) {
          
          
                return null;
            }
            Server server = null;
    
            while (server == null) {
          
          
                if (Thread.interrupted()) {
          
          
                    return null;
                }
                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
    
                int serverCount = allList.size();
                if (serverCount == 0) {
          
          
                    /*
                     * No servers. End regardless of pass, because subsequent passes
                     * only get more restrictive.
                     */
                    return null;
                }
    
    //            int index = chooseRandomInt(serverCount);
    //            server = upList.get(index);
                //============================================================
                if(total<5){
          
          
                    server = upList.get(currentIndex);
                    total++;
                }else {
          
          
                    total = 0;
                    currentIndex++;
                    if(currentIndex>upList.size()-1){
          
          //数组下标越界异常 -1
                        currentIndex = 0;
                    }
                    //从活着的服务中,获取指定的服务来进行操作
                    server = upList.get(currentIndex);
                }
                //============================================================
    
                if (server == null) {
          
          
                    /*
                     * The only time this should happen is if the server list were
                     * somehow trimmed. This is a transient condition. Retry after
                     * yielding.
                     */
                    Thread.yield();
                    continue;
                }
    
                if (server.isAlive()) {
          
          
                    return (server);
                }
    
                // Shouldn't actually happen.. but must be transient or a bug.
                server = null;
                Thread.yield();
            }
    
            return server;
    
        }
    
        protected int chooseRandomInt(int serverCount) {
          
          
            return ThreadLocalRandom.current().nextInt(serverCount);
        }
    
    
    
        @Override
        public Server choose(Object key) {
          
          
            return choose(getLoadBalancer(), key);
        }
        @Override
        public void initWithNiwsConfig(IClientConfig clientConfig) {
          
          
            // TODO Auto-generated method stub
        }
    }
    

Feign:负载均衡

7.1 Feign 简介

Feign是声明式Web Service客户端,它让微服务之间的调用变得更简单,类似controller调用service。SpringCloud集成了Ribbon和Eureka,可以使用Feigin提供负载均衡的http客户端

只需要创建一个接口,然后添加注解即可~

Feign,主要是社区版,大家都习惯面向接口编程。这个是很多开发人员的规范。调用微服务访问两种方法

  • 微服务名字 【ribbon】
  • 接口和注解 【feign】

Feign能干什么?

  • Feign旨在使编写Java Http客户端变得更容易
  • 前面在使用Ribbon + RestTemplate时,利用RestTemplate对Http请求的封装处理,形成了一套模板化的调用方法。但是在实际开发中,由于对服务依赖的调用可能不止一处,往往一个接口会被多处调用,所以通常都会针对每个微服务自行封装一个客户端类来包装这些依赖服务的调用。所以,Feign在此基础上做了进一步的封装,由他来帮助我们定义和实现依赖服务接口的定义,在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它 (类似以前Dao接口上标注Mapper注解,现在是一个微服务接口上面标注一个Feign注解),即可完成对服务提供方的接口绑定,简化了使用Spring Cloud Ribbon 时,自动封装服务调用客户端的开发量。

Feign默认集成了Ribbon

  • 利用Ribbon维护了MicroServiceCloud-Dept的服务列表信息,并且通过轮询实现了客户端的负载均衡,而与Ribbon不同的是,通过Feign只需要定义服务绑定接口且以声明式的方法,优雅而简单的实现了服务调用。

7.2 Fegin 的使用步骤

  1. 创建 springcloud-consumer-dept-feign 模块

    拷贝springcloud-consumer-dept-80模块下的pom.xml,resource,以及java代码到springcloud-consumer-feign模块,并添加feign依赖。

    <!--Feign的依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    
  2. 修改 springcloud-api 模块

    pom.xml添加feign依赖

    <!--Feign的依赖-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
        <version>1.4.6.RELEASE</version>
    </dependency>
    

    新建service包,并新建DeptClientService.java接口

    package com.kuang.springcloud.service;
    
    import com.kuang.springcloud.pojo.Dept;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.stereotype.Component;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    
    import java.util.List;
    // @FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
    @FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT-9000")
    public interface DeptClientService {
          
          
    
        @GetMapping("/dept/selectOne/{id}")
        public Dept selectOne(@PathVariable("id") Integer id);
    
        @PostMapping("/dept/add")
        public boolean addDept(Dept dept);
    
        @GetMapping("/dept/selectAll")
        public List<Dept> selectAll();
    }
    
    
  3. 修改 springcloud-consumer-dept-feign 下的 DeptConsumerController

    package com.kuang.springcloud.controller;
    
    import com.kuang.springcloud.pojo.Dept;
    import com.kuang.springcloud.service.DeptClientService;
    import org.springframework.beans.factory.annotation.Autowired;
    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;
    
    @RestController
    public class DeptConsumerController {
          
          
    
        /**
         *消费者:不应该有service层
         * RestTemplate 供我们直接调用,注册到spring中
         * (地址:URL,实体:Map,Class<T> responseType)
         * 提供多种便捷访问远程http服务的方法,简单的Restful服务模板~
         */
    //    @Autowired
    //    private RestTemplate restTemplate;
        @Autowired
        private DeptClientService deptClientService;
    
        /**
         * 服务提供方地址前缀
         * <p>
         * Ribbon:我们这里的地址,应该是一个变量,通过服务名来访问
         */
        //private static final String REST_URL_PREFIX="http://localhost:9000";
        //Ribbon 我们这里的地址,应该是一个变量,通过服务名来访问
        //private static final String REST_URL_PREFIX="http://SPRINGCLOUD-PROVIDER-DEPT-9000";
    
        /**
         * 消费方添加部门信息
         * @param dept
         * @return
         */
        @RequestMapping("/feign/dept/add")
        public boolean add(Dept dept){
          
          
            // postForObject(服务提供方地址(接口),参数实体,返回类型.class)
            //return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add",dept,Boolean.class);
            return deptClientService.addDept(dept);
        }
    
        /**
         * 消费方根据id查询部门信息
         * @param id
         * @return
         */
        @RequestMapping("/feign/dept/selectOne/{id}")
        public Dept selectOne(@PathVariable("id") Integer id){
          
          
            // getForObject(服务提供方地址(接口),返回类型.class)
            //return restTemplate.getForObject(REST_URL_PREFIX+"/dept/selectOne/"+id,Dept.class);
            return deptClientService.selectOne(id);
        }
    
        /**
         * 消费方查询部门信息列表
         * @return
         */
        @RequestMapping("/feign/dept/selectAll")
        public List<Dept> selectAll(){
          
          
            //return restTemplate.getForObject(REST_URL_PREFIX+"/dept/selectAll",List.class);
            return deptClientService.selectAll();
        }
    }
    
    
  4. 启动 7001,9000,9001,9002 和 springcloud-consumer-dept-feign 进行测试 访问 http://localhost/feign/dept/selectAll 多次刷新看到轮询效果

7.3 Feign 和 Ribbon 如何选择

根据个人习惯而定,如果喜欢REST风格使用Ribbon;如果喜欢社区版的面向接口风格使用Feign.

Feign 本质上也是实现了 Ribbon,只不过后者是在调用方式上,为了满足一些开发者习惯的接口调用习惯!

Hystrix:服务熔断

分布式系统面临的问题

复杂分布式体系结构中的应用程序有数十个依赖关系,每个依赖关系在某些时候将不可避免失败!

8.1 服务雪崩

多个微服务之间调用的时候,假设微服务A调用微服务B和微服务C,微服务B和微服务C又调用其他的微服务,这就是所谓的“扇出”,如果扇出的链路上某个微服务的调用响应时间过长,或者不可用,对微服务A的调用就会占用越来越多的系统资源,进而引起系统崩溃,所谓的“雪崩效应”。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-y8AebAt3-1674724143828)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20201121144830148.png)]

对于高流量的应用来说,单一的后端依赖可能会导致所有服务器上的所有资源都在几十秒内饱和。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,备份队列,线程和其他系统资源紧张,导致整个系统发生更多的级联故障,这些都表示需要对故障和延迟进行隔离和管理,以达到单个依赖关系的失败而不影响整个应用程序或系统运行

我们需要,弃车保帅

8.2 什么是 Hystrix?

Hystrix是一个应用于处理分布式系统的延迟和容错的开源库,在分布式系统里,许多依赖不可避免的会调用失败,比如超时,异常等,Hystrix 能够保证在一个依赖出问题的情况下,不会导致整个体系服务失败,避免级联故障,以提高分布式系统的弹性。

断路器”本身是一种开关装置,当某个服务单元发生故障之后,通过断路器的故障监控 (类似熔断保险丝) ,向调用方返回一个服务预期的,可处理的备选响应 (FallBack) ,而不是长时间的等待或者抛出调用方法无法处理的异常,这样就可以保证了服务调用方的线程不会被长时间,不必要的占用,从而避免了故障在分布式系统中的蔓延,乃至雪崩。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Fbym7WVb-1674724143828)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\2020112114554744.png)]

8.3 Hystrix 能干嘛

  • 服务降级
  • 服务熔断
  • 服务限流
  • 接近实时的监控
  • ……

官网资料https://github.com/Netflix/Hystrix/wiki

  • 当一切正常时,请求流可以如下所示:

    format_png 2

    当许多后端系统中有一个潜在阻塞服务时,它可以阻止整个用户请求:

    format_png 3

    随着大容量通信量的增加,单个后端依赖项的潜在性会导致所有服务器上的所有资源在几秒钟内饱和。

    应用程序中通过网络或客户端库可能导致网络请求的每个点都是潜在故障的来源。比失败更糟糕的是,这些应用程序还可能导致服务之间的延迟增加,从而备份队列、线程和其他系统资源,从而导致更多跨系统的级联故障。

    format_png 4

    当使用Hystrix包装每个基础依赖项时,上面的图表中所示的体系结构会发生类似于以下关系图的变化。每个依赖项是互隔离的,限制在延迟发生时它可以填充的资源中,并包含在回退逻辑中,该逻辑决定在依赖项中发生任何类型的故障时要做出什么样的响应:

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YSqV0Oyp-1674724143828)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20200521131820586.png)]相

8.4 服务熔断

什么是服务熔断?

熔断机制是赌赢雪崩效应的一种微服务链路保护机制

当扇出链路的某个微服务不可用或者响应时间太长时,会进行服务的降级,进而熔断该节点微服务的调用,快速返回错误的响应信息。检测到该节点微服务调用响应正常后恢复调用链路。在SpringCloud框架里熔断机制通过Hystrix实现。Hystrix会监控微服务间调用的状况,当失败的调用到一定阀值缺省是5秒内20次调用失败,就会启动熔断机制。熔断机制的注解是:@HystrixCommand

服务熔断解决如下问题:

  • 当所依赖的对象不稳定时,能够起到快速失败的目的;
  • 快速失败后,能够根据一定的算法动态试探所依赖对象是否恢复。

入门案例

新建 springcloud-provider-dept-hystrix-9000 拷贝 springcloud-provider-dept-9000 原始内容

导入Hystrix 依赖

<!--导入Hystrix依赖-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.6.RELEASE</version>
</dependency>

修改 application.yml

server:
  port: 9000

mybatis:
  type-aliases-package: com.kuang.springcloud.pojo
  config-location: classpath:mybatis/mybatis-config.xml
  mapper-locations: classpath:mybatis/mapper/*.xml
spring:
  application:
    name: springcloud-provider-dept-9000
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springcloud_kuang_db01?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456
# Eureka 配置:配置服务注册中心地址
eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
  # 修改eureka上的默认描述信息
  instance:
    instance-id: springcloud-provider-dept-hystrix-9000  #修改Eureka上的默认描述信息
    prefer-ip-address: true  #改为true后默认显示的是ip地址而不再是localhost
info:
  app.name: kuang-springcloud
  company.name: 河南师范大学

修改 DeptController

package com.kuang.springcloud.controller;

import com.kuang.springcloud.pojo.Dept;
import com.kuang.springcloud.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
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.*;

import java.util.List;

@RestController
public class DeptController {
    
    

    @Autowired
    private DeptService deptService;

    /**
     * 根据id查询部门信息
     * 如果根据id查询出现异常,则走hystrixGet这段备选代码
     * @param id
     * @return
     */
    @HystrixCommand(fallbackMethod = "chooseHystrix")
    @GetMapping("/dept/selectOne/{id}")
    public Dept selectOne(@PathVariable("id") Integer id){
    
    
        Dept dept = deptService.selectOne(id);
        if (dept == null){
    
    
            throw new RuntimeException("id=>"+id+" 不存在,信息无法被找到!");
        }
        return dept;
    }

    /**
     * 根据id查询备选方案
     * @param id
     * @return
     */
    public Dept chooseHystrix(Integer id){
    
    
        return new Dept().setDeptNo(id)
                .setDeptName("这个id没有对应的信息~")
                .setDbSource("No database in MySql");
    }

}

为主启动类添加对熔断的支持注解@EnableCircuitBreaker

package com.kuang.springcloud;

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

@SpringBootApplication
@EnableEurekaClient
// @EnableEurekaClient 开启Eureka客户端注解,在服务启动后自动向注册中心注册服务
@EnableDiscoveryClient
// @EnableDiscoveryClient 开启服务发现客户端的注解,可以用来获取一些配置的信息,得到具体的微服务
@EnableCircuitBreaker //添加对熔断的支持注解
public class springcloud_provider_dept {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(springcloud_provider_dept.class,args);
    }
}

测试

访问 http://localhost/consumer/dept/selectOne/9 使用熔断后,当访问一个不存在的id时,显示如下:

{
    
    "deptNo":9,"deptName":"这个id没有对应的信息~","dbSource":"No database in MySql"}

因此,为了避免因某个微服务后台出现异常或错误而导致整个应用或网页报错,使用熔断是必要的

8.5 服务降级

什么是服务降级

服务降级是指 当服务器压力剧增的情况下,根据实际业务情况及流量,对一些服务和页面有策略的不处理,或换种简单的方式处理,从而释放服务器资源以保证核心业务正常运作或高效运作。说白了,就是尽可能的把系统资源让给优先级高的服务

资源有限,而请求是无限的。如果在并发高峰期,不做服务降级处理,一方面肯定会影响整体服务的性能,严重的话可能会导致宕机某些重要的服务不可用。所以,一般在高峰期,为了保证核心功能服务的可用性,都要对某些服务降级处理。比如当双11活动时,把交易无关的服务统统降级,如查看蚂蚁深林,查看历史订单等等。

服务降级主要用于什么场景呢?当整个微服务架构整体的负载超出了预设的上限阈值或即将到来的流量预计将会超过预设的阈值时,为了保证重要或基本的服务能正常运行,可以将一些 不重要 或 不紧急 的服务或任务进行服务的 延迟使用 或 暂停使用。

降级的方式可以根据业务来,可以延迟服务,比如延迟给用户增加积分,只是放到一个缓存中,等服务平稳之后再执行 ;或者在粒度范围内关闭服务,比如关闭相关文章的推荐。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gBRYoIpL-1674724143829)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20200521132141732.png)]

由上图可得,当某一时间内服务A的访问量暴增,而B和C的访问量较少,为了缓解A服务的压力,这时候需要B和C暂时关闭一些服务功能,去承担A的部分服务,从而为A分担压力,叫做服务降级

服务降级需要考虑的问题

  • 1)那些服务是核心服务,哪些服务是非核心服务
  • 2)那些服务可以支持降级,那些服务不能支持降级,降级策略是什么
  • 3)除服务降级之外是否存在更复杂的业务放通场景,策略是什么?

自动降级分类

  • 1)超时降级:主要配置好超时时间和超时重试次数和机制,并使用异步机制探测回复情况
  • 2)失败次数降级:主要是一些不稳定的api,当失败调用次数达到一定阀值自动降级,同样要使用异步机制探测回复情况
  • 3)故障降级:比如要调用的远程服务挂掉了(网络故障、DNS故障、http服务返回错误的状态码、rpc服务抛出异常),则可以直接降级。降级后的处理方案有:默认值(比如库存服务挂了,返回默认现货)、兜底数据(比如广告挂了,返回提前准备好的一些静态页面)、缓存(之前暂存的一些缓存数据)
  • 4)限流降级:秒杀或者抢购一些限购商品时,此时可能会因为访问量太大而导致系统崩溃,此时会使用限流来进行限制访问量,当达到限流阀值,后续请求会被降级;降级后的处理方案可以是:排队页面(将用户导流到排队页面等一会重试)、无货(直接告知用户没货了)、错误页(如活动太火爆了,稍后重试)。

入门案例

在springcloud-api模块下的service包中新建降级配置类DeptClientServiceFallBackFactory.java

package com.kuang.springcloud.service;

import com.kuang.springcloud.pojo.Dept;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DeptClientServiceFallBackFactory implements FallbackFactory {
    
    
    @Override
    public DeptClientService create(Throwable throwable) {
    
    
        return new DeptClientService() {
    
    
            @Override
            public Dept selectOne(Integer id) {
    
    
                return new Dept()
                        .setDeptNo(id)
                        .setDeptName("id=>"+id+" 没有对应的信息,客户端提供降级信息,这个服务已经被关闭")
                        .setDbSource("No database in MySql");
            }

            @Override
            public boolean addDept(Dept dept) {
    
    
                return false;
            }

            @Override
            public List<Dept> selectAll() {
    
    
                return null;
            }
        };
    }
}

在DeptClientService中指定降级配置类DeptClientServiceFallBackFactory

package com.kuang.springcloud.service;

import com.kuang.springcloud.pojo.Dept;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
// @FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
//fallbackFactory指定降级配置类
@FeignClient(value = "SPRINGCLOUD-PROVIDER-DEPT-9000",fallbackFactory = DeptClientServiceFallBackFactory.class)
public interface DeptClientService {
    
    

    @GetMapping("/dept/selectOne/{id}")
    public Dept selectOne(@PathVariable("id") Integer id);

    @PostMapping("/dept/add")
    public boolean addDept(Dept dept);

    @GetMapping("/dept/selectAll")
    public List<Dept> selectAll();
}

springcloud-consumer-dept-feign模块中开启降级:

server:
  port: 80
#Eureka 配置
eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/

# 开启降级 feign.hystrix
feign:
  hystrix:
    enabled: true

启动测试

访问 http://localhost/feign/dept/selectOne/6 正常显示;当把 springcloud-provider-dept-9000 服务关闭后再次访问显示如下:

{
    
    "deptNo":6,"deptName":"id=>6 没有对应的信息,客户端提供降级信息,这个服务已经被关闭","dbSource":"No database in MySql"}

测试通过

8.6 服务熔断和服务降级的区别

  • 服务熔断—>服务端:某个服务超时或异常,引起熔断~,类似于保险丝(自我熔断)
  • 服务降级—>客户端:从整体网站请求负载考虑,当某个服务熔断或者关闭之后,服务将不再被调用,此时在客户端,我们可以准备一个 FallBackFactory ,返回一个默认的值(缺省值)。会导致整体的服务下降,但是好歹能用,比直接挂掉强。
  • 触发原因不太一样,服务熔断一般是某个服务(下游服务)故障引起,而服务降级一般是从整体负荷考虑;管理目标的层次不太一样,熔断其实是一个框架级的处理,每个微服务都需要(无层级之分),而降级一般需要对业务有层级之分(比如降级一般是从最外围服务开始)
  • 实现方式不太一样,服务降级具有代码侵入性(由控制器完成/或自动降级),熔断一般称为自我熔断

熔断、降级、限流:

  • 限流:限制并发的请求访问量,超过阈值则拒绝;
  • 降级:服务分优先级,牺牲非核心服务(不可用),保证核心服务稳定;从整体负荷考虑;
  • 熔断:依赖的下游服务故障触发熔断,避免引发本系统崩溃;系统自动执行和恢复

8.7 Dashboard 流监控

新建springcloud-consumer-hystrix-dashboard模块

pom.xml


    <dependencies>

        <!--Hystrix依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--dashboard依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Ribbon-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--实体类+web-->
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>

    </dependencies>
</project>

主启动类

package com.kuang.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.hystrix.dashboard.EnableHystrixDashboard;

@SpringBootApplication
// 开启Dashboard
@EnableHystrixDashboard
public class DeptConsumerDashboard_8888 {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DeptConsumerDashboard_8888.class,args);
    }
}

给springcloud-provider-dept-hystrix-9000模块下的主启动类添加如下代码,添加监控

package com.kuang.springcloud;

import com.netflix.hystrix.contrib.metrics.eventstream.HystrixMetricsStreamServlet;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableEurekaClient
// @EnableEurekaClient 开启Eureka客户端注解,在服务启动后自动向注册中心注册服务
@EnableDiscoveryClient
// @EnableDiscoveryClient 开启服务发现客户端的注解,可以用来获取一些配置的信息,得到具体的微服务
@EnableCircuitBreaker //添加对熔断的支持注解
public class springcloud_provider_dept {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(springcloud_provider_dept.class,args);
    }

    @Bean
    public ServletRegistrationBean hystrixMetricsStreamServlet(){
    
    
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new HystrixMetricsStreamServlet());
        //访问该页面就是监控页面
        servletRegistrationBean.addUrlMappings("/actuator/hystrix.stream");
        return servletRegistrationBean;
    }
}

启动测试

  • 同时开启 springcloud-provider-dept-hystrix-9000、springcloud-eureka-7001、springcloud-consumer-hystrix-dashboard、springcloud-consumer-dept-feign
  • 访问 http://localhost:9000/actuator/hystrix.stream 可以看到相关信息

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-4wEO4nOa-1674724143829)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673355133844.png)]

  • 访问 http://localhost:8888/hystrix 输入相关信息,进入监控页面

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3oZ2P2Zr-1674724143829)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673355336492.png)]

  • 不停地访问 http://localhost/feign/dept/selectOne/7 可以看到如下效果

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ikEEDqgc-1674724143829)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673355520008.png)]

Zull:路由网关

什么是zull?

Zull包含了对请求的路由(用来跳转的)和过滤两个最主要功能:

其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础,而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验,服务聚合等功能的基础。Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他服务的消息,也即以后的访问微服务都是通过Zuul跳转后获得。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ywW0GTJs-1674724143829)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\20201122103018821.png)]

注意:Zuul 服务最终还是会注册进 Eureka

提供:代理 + 路由 + 过滤 三大功能!

zuul能干嘛?

  • 路由
  • 过滤

官方文档:https://github.com/Netflix/zuul/

入门案例

  • 新建springcloud-zuul模块,并导入依赖

    <dependencies>
        <!--导入zuul依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Hystrix依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--dashboard依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-hystrix-dashboar</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Ribbon-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--Eureka-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
            <version>1.4.6.RELEASE</version>
        </dependency>
        <!--实体类+web-->
        <dependency>
            <groupId>com.haust</groupId>
            <artifactId>springcloud-api</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--热部署-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>
    
  • application.yml

    server:
      port: 9527
    spring:
      application:
        name: springcloud-zuul #微服务名称
    #Eureka 注册中心
    eureka:
      client:
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
      # 修改eureka上的默认描述信息
      instance:
        instance-id: zuul9527.com  #修改Eureka上的默认描述信息
        prefer-ip-address: true  #改为true后默认显示的是ip地址而不再是localhost
    info:
      app.name: kuang-springcloud  #项目名称
      company.name: 河南师范大学     #公司名称
    #zuul:
    #  routes:
    #    mydept.serviceId: SPRINGCLOUD-PROVIDER-DEPT-9000
    #    mydept.path: /mydept/**
    #  ignored-services: "*"
    #  prefix: /kuang
    
    
  • 启动类

    package com.kuang.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
    
    @SpringBootApplication
    @EnableZuulProxy  //开启zuul
    public class ZuulApplication_9527 {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(ZuulApplication_9527.class,args);
        }
    }
    
    
  • 测试

    • 启动 7001,springcloud-provider-dept-9000,9527

    • 访问 http://localhost:7001/

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3QeZ92at-1674724143830)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673506029285.png)]

    • 访问 http://localhost:9000/dept/selectOne/1

      {
              
              "deptNo":1,"deptName":"开发部","dbSource":"springcloud_kuang_db01"}
      
    • 访问 http://xiaotengteng.com:9527/springcloud-provider-dept-9000/dept/selectOne/1

      # 127.0.0.1 xiaotengteng.com
      # springcloud-provider-dept-9000 对应 SPRINGCLOUD-PROVIDER-DEPT-9000 访问大写报错
      {
              
              "deptNo":1,"deptName":"开发部","dbSource":"springcloud_kuang_db01"}
      
  • 修改 application.yml

    server:
      port: 9527
    spring:
      application:
        name: springcloud-zuul #微服务名称
    #Eureka 注册中心
    eureka:
      client:
        service-url:
          defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
      # 修改eureka上的默认描述信息
      instance:
        instance-id: zuul9527.com  #修改Eureka上的默认描述信息
        prefer-ip-address: true  #改为true后默认显示的是ip地址而不再是localhost
    info:
      app.name: kuang-springcloud  #项目名称
      company.name: 河南师范大学     #公司名称
    zuul:
      routes:
        mydept.serviceId: SPRINGCLOUD-PROVIDER-DEPT-9000 # eureka注册中心的服务提供方路由名称
        mydept.path: /mydept/**   # 将eureka注册中心的服务提供方路由名称 改为自定义路由名称
      ignored-services: "*"  # 不能再使用这个路径访问了,*: 忽略,隐藏全部的服务名称~
      prefix: /kuang # 设置公共的前缀
    
    
  • 再次测试,不加 prefix: /kuang

    • 访问 http://xiaotengteng.com:9527/mydept/dept/selectOne/2

      {
              
              "deptNo":2,"deptName":"人事部","dbSource":"springcloud_kuang_db01"}
      
    • 访问 http://xiaotengteng.com:9527/springcloud-provider-dept-9000/dept/selectOne/1

      Whitelabel Error Page
      This application has no explicit mapping for /error, so you are seeing this as a fallback.
      
      Thu Jan 12 15:23:05 CST 2023
      There was an unexpected error (type=Not Found, status=404).
      No message available
      # 测试成功
      
  • 再次测试 ,添加 prefix: /kuang 后

    • 访问 http://xiaotengteng.com:9527/mydept/dept/selectOne/2

      Whitelabel Error Page
      This application has no explicit mapping for /error, so you are seeing this as a fallback.
      
      Thu Jan 12 15:23:05 CST 2023
      There was an unexpected error (type=Not Found, status=404).
      No message available
      
      # 测试成功
      
    • 访问 http://xiaotengteng.com:9527/kuang/mydept/dept/selectOne/3

      {
              
              "deptNo":3,"deptName":"财务部","dbSource":"springcloud_kuang_db01"}
      
  • 注意

    访问路径 http://xiaotengteng.com:9527/kuang/mydept/dept/selectOne/3

    • xiaotengteng.com:对应 127.0.0.1,(与 eureka7001.com相同,本质还是localhost)

    • kuang:路由前缀

    • mydept:替换并隐藏微服务名称

    • /dept/selectOne/3:指定服务下的路由接口 (springcloud-provider-dept-9000)

Spring Cloud Config 分布式配置

环境搭建

  1. 新建 Gitee 仓库,复制ssh链接

    [email protected]:gonetgt/springcloud-config.git
    
  2. 克隆项目到本地,并新建application.yml文件上传至远程仓库

    • 进入要存放的文件夹,鼠标右键 点击 Git Bash Here

    • 输入克隆命令:git clone ssh链接

      $ git clone [email protected]:gonetgt/springcloud-config.git
      
    • 查看是否下载成功

      # 显示如下信息需要配置 ssh公钥
      [email protected]: Permission denied (publickey).
      fatal: Could not read from remote repository.
      
      Please make sure you have the correct access rights
      and the repository exists.
      
      # 配置完成后再次输入命令
      $ git clone [email protected]:gonetgt/springcloud-config.git
      Cloning into 'springcloud-config'...
      remote: Enumerating objects: 6, done.
      remote: Counting objects: 100% (6/6), done.
      remote: Compressing objects: 100% (6/6), done.
      remote: Total 6 (delta 0), reused 0 (delta 0), pack-reused 0
      Receiving objects: 100% (6/6), 14.21 KiB | 7.11 MiB/s, done.
      #克隆到本地成功
      
    • 进入到克隆后的目录下,新建application.yml

      spring:
          profiles:
              active: dev  
      ---
      spring:
          profiles: dev
          application:
              name: springcloud-config-dev
      ---
      spring:
          profiles: test
          application:
              name: springcloud-config-test
      
    • 右键 点击 Git Bash Here

      • 输入 : git add .
      # 被修改的所有文件提交到暂存区
      $ git add .
      
      • 输入 :git status

        # 查看状态 
        $ git status
        On branch master
        Your branch is up to date with 'origin/master'.
        
        Changes to be committed:
          (use "git restore --staged <file>..." to unstage)
                new file:   application.yml
        
      • 输入 :git commit -m "first commit

        # git commit 提交命令 -m 表示要提交的消息
        $ git commit -m "first commit"
        [master 61ede4f] first commit
         1 file changed, 13 insertions(+)
         create mode 100644 application.yml
        
      • 输入:git push origin master

        # git push 提交到远程仓库命令
        # origin 代表当前用户
        # master 代表要push的分支
        $ git push origin master
        Enumerating objects: 4, done.
        Counting objects: 100% (4/4), done.
        Delta compression using up to 8 threads
        Compressing objects: 100% (3/3), done.
        Writing objects: 100% (3/3), 369 bytes | 369.00 KiB/s, done.
        Total 3 (delta 1), reused 0 (delta 0), pack-reused 0
        remote: Powered by GITEE.COM [GNK-6.4]
        To gitee.com:gonetgt/springcloud-config.git
           ee72ae6..61ede4f  master -> master
        
    • 查看是否上传到远程仓库

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rioTvGgQ-1674724143830)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673533257670.png)]

  3. 环境搭建完成

概述

分布式系统面临的–配置文件问题

微服务意味着要将单体应用中的业务拆分成一个个子服务,每个服务的粒度相对较小,因此系统中会出现大量的服务,由于每个服务都需要必要的配置信息才能运行,所以一套集中式的,动态的配置管理设施是必不可少的。spring cloud提供了configServer来解决这个问题,我们每一个微服务自己带着一个application.yml,那上百个的配置文件修改起来,令人头疼!

什么是SpringCloud config分布式配置中心?

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DnBGNDjl-1674724143830)(C:\Users\戴尔\所有文件\Markdown\kuang\微服务开发\picture\1673619843067.png)]

spring cloud config 为微服务架构中的微服务提供集中化的外部支持,配置服务器为各个不同微服务应用的所有环节提供了一个中心化的外部配置

spring cloud config 分为服务端客户端两部分。

服务端也称为 分布式配置中心,它是一个独立的微服务应用,用来连接配置服务器并为客户端提供获取配置信息,加密,解密信息等访问接口。

客户端则是通过指定的配置中心来管理应用资源,以及与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。配置服务器默认采用git来存储配置信息,这样就有助于对环境配置进行版本管理。并且可用通过git客户端工具来方便的管理和访问配置内容。

spring cloud config 分布式配置中心能干嘛?

  • 集中式管理配置文件
  • 不同环境,不同配置,动态化的配置更新,分环境部署,比如 /dev /test /prod /beta /release
  • 运行期间动态调整配置,不再需要在每个服务部署的机器上编写配置文件,服务会向配置中心统一拉取配置自己的信息
  • 当配置发生变动时,服务不需要重启,即可感知到配置的变化,并应用新的配置
  • 将配置信息以REST接口的形式暴露

spring cloud config 分布式配置中心与GitHub整合

由于spring cloud config 默认使用git来存储配置文件 (也有其他方式,比如自持SVN 和本地文件),但是最推荐的还是git ,而且使用的是 http / https 访问的形式。

入门案例

  • 服务端

    新建springcloud-config-server-3344模块

    pom.xml

        <dependencies>
            <!--web-->
          <dependency>
                <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--config-->
            <dependency>
              <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-config-server</artifactId>
              <version>2.1.1.RELEASE</version>
            </dependency>
            <!--actuator完善监控信息-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
        </dependencies>
    

    resource下创建application.yml配置文件,Spring Cloud Config服务器从git存储库(必须提供)为远程客户端提供配置:

    server:
      port: 3344
    
    spring:
      application:
        name: springcloud-config-server
      cloud:
        config:
          server:
            git:
              uri: https://gitee.com/gonetgt/springcloud-config.git
    

    主启动类

    package com.kuang.springcloud;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.config.server.EnableConfigServer;
    
    @EnableConfigServer // 开启spring cloud config server服务
    @SpringBootApplication
    public class Config_server_3344 {
          
          
        public static void main(String[] args) {
          
          
            SpringApplication.run(Config_server_3344.class,args);
        }
    }
    

    以下参考spring 中文文档:Spring Cloud 配置 | 中文文档 (gitcode.net)

    • 定位属性源的默认策略是克隆一个 Git 存储库(atspring.cloud.config.server.git.uri),并使用它初始化一个 miniSpringApplication。迷你应用程序的Environment用于枚举属性源并在 JSON 端点上发布它们。

    • HTTP 服务具有以下形式的资源:

      /{application}/{profile}[/{label}]
      /{application}-{profile}.yml
      /{label}/{application}-{profile}.yml
      /{application}-{profile}.properties
      /{label}/{application}-{profile}.properties
      
    • 其中applicationSpringApplication中被注入为spring.config.name(在常规 Spring 引导应用程序中通常application),profile是一个活动配置文件(或逗号分隔的属性列表),而label是一个可选的 git 标签(默认为master)。

    启动测试:

    • 启动:springcloud-eureka-7001、springcloud-config-server-3344

      访问:http://localhost:3344/application-dev.yml

      spring:
        application:
          name: springcloud-config-dev
        profiles:
          active: dev
      
    • 访问:http://localhost:3344/application/test/master

      {
              
              "name":"application","profiles":["test"],"label":"master","version":"61ede4f878ca102060e71b4449cbf1a2b18d840b","state":null,"propertySources":[{
              
              "name":"https://gitee.com/gonetgt/springcloud-config.git/application.yml (document #2)","source":{
              
              "spring.profiles":"test","spring.application.name":"springcloud-config-test"}},{
              
              "name":"https://gitee.com/gonetgt/springcloud-config.git/application.yml (document #0)","source":{
              
              "spring.profiles.active":"dev"}}]}
      
    • Visit: http://localhost:3344/master/application-dev.yml

      spring:
        application:
          name: springcloud-config-dev
        profiles:
          active: dev
      
    • The remaining two formats are self-tested

      Access non-existing configuration: http://localhost:3344/master/application-kuang.yml

      spring:
        profiles:
          active: dev
      
  • client

    • Create a new config-server.yml under the springcloud-config folder of the local git warehouse

      spring:
        profile:
          active: dev
      ---
      server:
        port: 8201
      spring:
        profile: dev
        application:
          name: springcloud-provider-dept-9000
      eureka:
        client:
          service-url:
            defaultZone: http://eureka7001.com:7001/eureka/
      ---
      server:
        port: 8202
      spring:
        profile: test
        application:
          name: springcloud-provider-dept-9000
      eureka:
        client:
          service-url:
            defaultZone: http://eureka7001.com:7001/eureka/
      
    • Submit to remote warehouse (omitted)

    • Create a new springcloud-config-client-3355 module

      pom.xml

          <dependencies>
              <dependency>
                <groupId>org.springframework.cloud</groupId>
                  <artifactId>spring-cloud-starter-config</artifactId>
                <version>2.1.1.RELEASE</version>
              </dependency>
            <dependency>
                  <groupId>org.springframework.boot</groupId>
                  <artifactId>spring-boot-starter-actuator</artifactId>
              </dependency>
            <dependency>
                  <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
              </dependency>
          </dependencies>
      

      Create application.yml and bootstrap.yml configuration files under resources

      bootstrap.yml: system level configuration

        spring:
        cloud:
            config:
              name: config-client   # 从 git 上读取资源(config-client.yml)
              profile: dev
            label: master
              uri: http://localhost:3344
      

      application.yml: user-level configuration

        spring:
          application:
            name: springcloud-config-client
      

      Create ConfigClientController.java under the controller package for testing

      @RestController
      public class ConfigClientController {
              
              
          @Value("${spring.application.name}")
          private String applicationName; //获取微服务名称
          @Value("${eureka.client.service-url.defaultZone}")
          private String eurekaServer; //获取Eureka服务
          @Value("${server.port}")
          private String port; //获取服务端的端口号
          @RequestMapping("/config")
          public String getConfig(){
              
              
              return "applicationName:"+applicationName +
               "eurekaServer:"+eurekaServer +
               "port:"+port;
          }
      }
      

      main startup class

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

      Start the test:

      Failed to display successfully, to be improved!

      Other content and pictures are to be improved!

Guess you like

Origin blog.csdn.net/Htupc/article/details/128766405