springCloud学习笔记(一)

学习参考:

https://blog.csdn.net/eson_15/article/details/83585344

https://my.oschina.net/u/3244751/blog/2923421

第一节 分布式架构理解
1、单体应用:用户---电商系统---数据库  

2、单体应用采用分布式部署集群:负载均衡---电商系统1,2,3 ---主从库---缓存集群  适合百万数据量

 单体应用缺点:开发速度慢,启动时间长,依赖庞大

3、微服务:负载均衡,多个节点高可用 LVS+keepLive 负载分发 ---网关集群 APIGetway ----每个服务抽出来,商品服务,订单服务--商品数据库,订单数据库,数据库切分减少压力,也可以通过nosql数据库缓存

微服务优点:易开发,理解和维护,独立部署和启动等,缺点分布式事务处理,服务治理

第二节 核心组件理解

1、网关:路由转发+过滤器

/api/v1/product/  商品服务

/api/v1/order/ 订单服务

/api/v1/user 用户服务

2、注册中心:维护调用与被调用方的信息

3、配置中心:管理配置动态更新  例application.properties,有可视化管理后台方便管理

4、链路追踪:分析调用链路耗时

5、负载均衡:分发负载

6、熔断:开启后,保护自己和被调用方

第三节 常见开源微服务框架

consumer  调用方

provider 被调用方

1、dubbo: zookeeper + dubbo + springmvc/springboot
官⽅方地址:http://dubbo.apache.org/#!/?lang=zh-cn
配套
通信⽅方式:rpc(速度快)
注册中⼼心:zookeper/redis
配置中⼼心:diamond
2、springcloud: 全家桶+轻松嵌⼊入第三⽅方组件(Netflix 奈奈⻜飞)
官⽹网:http://projects.spring.io/spring-cloud/
配套
通信⽅方式:http restful  (http涉及三次握手协议速度比rpc慢)
注册中⼼心:eruka/consul
配置中⼼心:config
断路路器器:hystrix
⽹网关:zuul
分布式追踪系统:sleuth+zipkin
学习资料料:https://blog.csdn.net/zhangweiwei2020/article/details/78646252 

第四节 分布式应用知识CAP理论知识及注册中心选择

CAP定理:Consistency一致性,Availability可用性,Partition tolerance 分区容错性,三者不可同时 获得只能3选2,由于网络硬件肯定会出现延迟丢包等问题,所以分区容错性必须要实现,所以只能在一致性和可用性之间权衡利弊

一致性,所有节点在同一时间数据是完全一致的

可用性,服务一直可用,而且是正常响应时间内

分区容错性,高可用性,一个节点崩了并不影响其他节点

第五节  搭建注册中心

参考 springcloud 中文官方文档  https://springcloud.cc/spring-cloud-dalston.html#spring-cloud-eureka-server

创建父项目,子项目

https://blog.csdn.net/weixin_38970805/article/details/82463122

踩坑:

1、创建子项目时报错无法访问https://start.spring.io连接超时?

解决:https://blog.csdn.net/lidai352710967/article/details/81089305  参考网上解决办法都不好用,换个网络就好了。

2、eureka server下载依赖时报错java.lang.AbstractMethodError? 启动时报错java.lang.NoSuchMethodError: org.springframework.boot.builder.SpringApplicationBuilder?

解决:都是springBoot版本问题,修改版本 改成2.1.3,保持父项目子项目版本一致。

3、application.properties 文件后缀改成 .yml,图标变成文本?

解决:直接重命名后缀由.properties改成 .yml,下载YAML插件,idea设置  setting- Editor-File Types ,YAML选项里添加  *.yml ,应用-保存,重启idea。

4、Eureka服务启动报错?

java.lang.IllegalStateException: Failed to load property source from location 'classpath:/application.yml'

org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input length = 1  ?

解决:yml文件编码格式问题,中文注释删除就能正常启动。

访问: 服务启动成功,localhost:端口号,即可访问。

5、配置maven找不到setting.xml文件 ?

解决办法:用的idea自带的maven插件 setting.xml 默认位置在idea文件下面  D:\idea\plugins\maven\lib\maven3\conf\settings.xml ,不用配置环境变量。

如安装外部maven需要配置环境变量,setting文件默认位置c:\Users\.m2\settings.xml

6、创建maven项目下载依赖特别慢?

解决办法:修改maven中央仓库地址,改成阿里云中央仓库

 打开maven3\conf\settings.xml , 找到mirrors标签。 替换如下配置,替换后修改成idea里的maven路径,即可

    <mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>       
    </mirror>
  </mirrors>

7、maven重新下载依赖jar包?

第六节 常用服务间调用方式

RPC:远程调用,长链接,支持同步异步,客户端与服务端之间建立TCP连接,可以一次建立一个,也可以多个调用服用一个链接,数据包小(协议会用谷歌的protobuf),

编解码,序列化,链接,丢包,拆包,组合

Rest(HTTP):http请求,支持多种协议和功能,开发方便成本低,http数据包大

HttpClient , URLConnection(jdk 自带的)

* 练习商品服务,订单服务,将服务注册导注册中心上

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Lombok插件

作用解决代码冗余省去getset方法,idea下载插件 setting--plugins--Browose repositories ---搜索lombok---install,

踩坑:

1、在idea里下载lombok插件后需要添加 maven依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

maven父工程

maven子工程

2、idea安装lombok插件后要配置两个地方勾选了 File-setting-complier-Annotation Processors- 勾选Enable Annotation

Processing,File-setting-complier-Java complier - module bytecode version 版本都改成1.8 ,然后重启

 

3、* 注意jdk1.8版本和lombok1.18.12版本可以兼容,lombok版本和jdk版本不兼容也会导致注解无法引入。

以上三点修改后重启idea,成功引入lombok注解

第七节 搭建商品服务,服务注册到Eureka,负载均衡

同时注册两个服务

负载均衡,通过注解 @LoadBalanced 和  RestTemplate模板类  进行服务间 调用

RestTemplat是spring提供了一种简单便捷的模板类,功能强大。

// GET请求
//getForEntity方法,返回值是一个ResponseEntity<T>是Spring对HTTP请求响应的封装,包括了几个重要的元素,如响应码、contentType、contentLength、响应消息体等
//返回值除了String 也可以是自定义类型,例如ResponseEntity<ProductOrder>
//getForEntity还有其他重载方法
ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://product-service/api/v1/product/find", String.class);

//getForObject方法,是对getForEntity函数的进一步封装,返回消息体的内容。getForObject还有其他重载方法
productOrder = restTemplate.getForObject("http://product-service/api/v1/product/find", ProductOrder.class);

//带参数的方法一
ResponseEntity<String> responseEntity2 = restTemplate.getForEntity("http://product-service/api/v1/product/find?name={1}", String.class, "赵赵");
//带参数的方法二
Map<String, String> map = new HashMap<>();
map.put("name", "李李");
ResponseEntity<String> responseEntity3 = restTemplate.getForEntity("http://product-service/api/v1/product/find?name={name}", String.class, map);

//调用地址也可以是URI
UriComponents uriComponents = UriComponentsBuilder.fromUriString("http://product-service/api/v1/product/find?name={name}").build().expand("钱钱").encode();
URI uri = uriComponents.toUri();
ResponseEntity<String> responseEntity4 = restTemplate.getForEntity(uri, String.class);

//POST请求
//postForEntity方法,postForObject方法,postForLocation方法
//参数一表示要调用的服务的地址,参数二表示上传的参数,参数三表示返回的消息体的数据类型
ResponseEntity<ProductOrder>  responseEntity5 = restTemplate.postForEntity("http://product-service/api/v1/product/find",productOrder,ProductOrder.class);
Object obj  =  restTemplate.postForObject("http://product-service/api/v1/product/find"  ,productOrder , Object.class  );

//PUT请求
//put方法没有返回值
restTemplate.put("http://product-service/api/v1/product/find/{1}" ,productOrder,1);

//DETETE请求
restTemplate.delete("http://product-service/api/v1/product/find/{1}", 2);

扩展:  设置拦截器ClientHttpRequestInterceptor(转)

有时候我们需要对请求做一些通用的拦截设置,这就可以使用拦截器进行处理。拦截器需要我们实现org.springframework.http.client.ClientHttpRequestInterceptor接口自己写。

举个简单的例子,写一个在header中根据请求内容和地址添加令牌的拦截器。

public class TokenInterceptor implements ClientHttpRequestInterceptor
{
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException
    {
        //请求地址
        String checkTokenUrl = request.getURI().getPath();
        //token有效时间
        int ttTime = (int) (System.currentTimeMillis() / 1000 + 1800);
        //请求方法名 POST、GET等
        String methodName = request.getMethod().name();
        //请求内容
        String requestBody = new String(body);
        //生成令牌 此处调用一个自己写的方法,有兴趣的朋友可以自行google如何使用ak/sk生成token,此方法跟本教程无关,就不贴出来了
        String token = TokenHelper.generateToken(checkTokenUrl, ttTime, methodName, requestBody);
        //将令牌放入请求header中
        request.getHeaders().add("X-Auth-Token",token);

        return execution.execute(request, body);
    }
}

  创建RestTemplate实例的时候可以这样向其中添加拦截器

        RestTemplate restTemplate = new RestTemplate();
        //向restTemplate中添加自定义的拦截器
        restTemplate.getInterceptors().add(new TokenInterceptor());

踩坑1:Eureka上注册过的订单服务已经停用了,注册信息在Eureka上还显示up,重启订单服务显示端口号被占用?

Eureka的自我保护机制,

# 以下配置仅在开发环境中使用
# 关闭注册中心的自我保护机制,防止已关闭的实例无法从注册中心剔除
eureka.server.enable-self-preservation=false

踩坑2:重启Eureka ,提示端口号被占用?

cmd 命令 netstat -ano | findstr  端口号 找到占用端口的服务的PID 

然后打开任务管理器找到 这个PID的服务,点击结束进程,重启服务即可

Ribbon负载均衡使用

Ribbon负载均衡源码学习

分析@LoadBalanced 

a.从注册中心获取provider列表

b.通过一定的策略选择其中一个节点(源码里有很多规则,默认规则是轮询 RoundRobinRule ,还有随机等其他规则)

c.再返回给restTemplate调用

踩坑1:idea重新打开项目,maven依赖红色报错,注解和引入jar都报错?

解决方法:检查maven配置,setting.xml文件不存在,自己在对应目录下新建一个,重新添加maven依赖点击install后刷新 ,解决。

setting.xml文件 ,直接复制下面内容创建即可。里面配置了阿里云路径

<?xml version="1.0" encoding="UTF-8"?>
 
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->
 
<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single
 |                 user, and is normally provided in
 |                 ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all
 |                 Maven users on a machine (assuming they're all using the
 |                 same Maven installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start
 | at getting the most out of your Maven installation. Where appropriate, the
 | default values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
 
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->
  <!--<localRepository>C:/Users/Administrator/.m2/repository</localRepository>  -->
  <localRepository>D:\Maven\repository</localRepository>
  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set
   | to false, maven will use a sensible default value, perhaps based on some
   | other setting, for the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->
  <!-- offline
   | Determines whether maven should attempt to connect to the network when
   | executing a build. This will have an effect on artifact downloads,
   | artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->
  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when
   | resolving plugins by their prefix, i.e. when invoking a command line like
   | "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
   | already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>
  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to
   | the network. Unless otherwise specified (by system property or command-
   | line switch), the first proxy specification in this list marked as active
   | will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>
 
  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used
   | within the system. Authentication profiles can be used whenever maven must
   | make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a
     | particular server, identified by a unique name within the system
     | (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR
     |       privateKey/passphrase, since these pairings are used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->
 
    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>
 
  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote
   | repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving
   | certain artifacts. However, this repository may have problems with heavy
   | traffic at times, so people have mirrored it to several places.
   |
   | That repository definition will have a unique id, so we can create a
   | mirror reference for that repository, to be used as an alternate download
   | site. The mirror site will be the preferred server for that repository.
   |-->
  <mirrors>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository.
     | The repository that this mirror serves has an ID that matches the
     | mirrorOf element of this mirror. IDs are used for inheritance and direct
     | lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
 
    <mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>central</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways,
   | and which can modify the build process. Profiles provided in the
   | settings.xml are intended to provide local machine-specific paths and
   | repository locations which allow the build to work in the local
   | environment.
   |
   | For example, if you have an integration testing plugin - like cactus -
   | that needs to know where your Tomcat instance is installed, you can
   | provide a variable here such that the variable is dereferenced during the
   | build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One
   | way - the activeProfiles section of this document (settings.xml) - will be
   | discussed later. Another way essentially relies on the detection of a
   | system property, either matching a particular value for the property, or
   | merely testing its existence. Profiles can also be activated by JDK
   | version prefix, where a value of '1.4' might activate a profile when the
   | build is executed on a JDK version of '1.4.2_07'. Finally, the list of
   | active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to
   |       specifying only artifact repositories, plugin repositories, and
   |       free-form properties to be used as configuration variables for
   |       plugins in the POM.
   |
   |-->
 
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated
     | using one or more of the mechanisms described above. For inheritance
     | purposes, and to activate profiles via <activatedProfiles/> or the
     | command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a
     | consistent naming convention for profiles, such as 'env-dev',
     | 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
     | will make it more intuitive to understand what the set of introduced
     | profiles is attempting to accomplish, particularly when you only have a
     | list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and
     | provides a JDK-specific repo.
     
    <profile>
      <id>jdk-1.4</id>
      <activation>
        <jdk>1.4</jdk>
      </activation>
      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env'
     | with a value of 'dev', which provides a specific path to the Tomcat
     | instance. To use this, your plugin configuration might hypothetically
     | look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone
     |       set 'target-env' to anything, you could just leave off the
     |       <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>
      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>
      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
    
    <profile>    
        <id>jdk-1.8</id>    
         <activation>    
            <activeByDefault>true</activeByDefault>    
            <jdk>1.8</jdk>    
          </activation>    
        <properties>    
            <maven.compiler.source>1.8</maven.compiler.source>    
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion> 
        </properties>    
    </profile>
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>


ribbon 自定义负载均衡策略, 在配置文件application.yml里面,自定义添加下面配置
        #自定义负载均衡策略
        product-service:
          ribbon:
            NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

    策略选择:
        1、如果每个机器配置一样,则建议不修改策略 (推荐)
        2、如果部分机器配置强,则可以改为 WeightedResponseTimeRule


        1、使用feign步骤讲解(新旧版本依赖名称不一样)
            加入依赖
                 <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-starter-openfeign</artifactId>
                </dependency>
            启动类增加@EnableFeignClients
            增加一个接口 并@FeignClient(name="product-service")
       2、注意点:
            1、路径
            2、Http方法必须对应
            3、使用requestBody,应该使用@PostMapping
            4、多个参数的时候,通过@RequestParam("id") int id)方式调用

1、ribbon和feign两个的区别和选择
            选择feign
                默认集成了ribbon
                写起来更加思路清晰和方便
                采用注解方式进行配置,配置熔断等方式方便

        2、超时配置
            默认optons readtimeout是60s,但是由于hystrix默认是1s超时,所以需要feign配置超时时间,配置后正常使用

            #修改调用超时时间
            feign:
              client:
                config:
                  default:
                    connectTimeout: 2000
                    readTimeout: 2000

            模拟接口响应慢,线程睡眠新的方式
              try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

第八节 熔断和降级

熔断:为了防止整个系统故障,含子和下游服务

降级:抛弃一些非核心的接口和数据

区别: 1、服务熔断一般由下游故障导致的,服务降级是从整体系统负荷考虑的,有调方控制

相同点:1、从可用性和可靠性触发,为了防止系统崩溃  2、最终让用户体验到的是某些功能的暂时不能用\

hystrix配置及使用

1、pom.xml文件引入依赖

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

2、启动类加注解 @EnableCircuitBreaker   此注解可以用@SpringCloudApplication 替代

3、实战测试,关闭商品服务时,浏览器访问http://localhost:8781/api/v1/order/save?product_id=1&user_id=4 返回提示,测试成功。

熔断后,如果产品服务恢复了会重新注册到注册中心,订单服务会隔一段时间就去注册中心获取,获取到hystrix就会尝试重连,

重连成功订单服务可以正常调用产品服务了,所以熔断后,被熔断的服务恢复正常,等一下系统就会自动恢复。

熔断监控报警机制

redis配置依赖

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

 

    1、查看默认讲解策略 HystrixCommandProperties
        1)execution.isolation.strategy   隔离策略
            THREAD 线程池隔离 (默认)
            SEMAPHORE 信号量
                信号量适用于接口并发量高的情况,如每秒数千次调用的情况,导致的线程开销过高,通常只适用于非网络调用,执行速度快

        2)execution.isolation.thread.timeoutInMilliseconds  超时时间
            默认 1000毫秒

        3)execution.timeout.enabled 是否开启超时限制 (一定不要禁用)


        4)execution.isolation.semaphore.maxConcurrentRequests 隔离策略为 信号量的时候,如果达到最大并发数时,后续请求会被拒绝,默认是10

#设置hystrix超时时间4秒,不配置默认是1秒
hystrix:
    command:
      default:
        execution:
          isolation:
            thread:
              timeoutInMilliseconds: 4000

    官方文档: https://github.com/Netflix/Hystrix/wiki/Configuration#execution.isolation.strategy

第九节 配置断路器Dashboard监控

1、加入依赖
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
        </dependency>

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

 2、启动类增加注解
        @EnableHystrixDashboard

  3、配置文件增加endpoint
management:
  endpoints:
    web:
      exposure:
        include: "*"

    4、访问入口
        http://localhost:8781/hystrix

        Hystrix Dashboard输入: http://localhost:8781/actuator/hystrix.stream 

页面报错:Unable to connect to Command Metric Stream

解决办法:application。yml 里 添加配置,成功解决,参考资料 https://www.jianshu.com/p/0a682e4781b0 

hystrix:
  dashboard:
    proxy-stream-allow-list: "localhost"

显示面板

断路器阈值有默认值 ,请求达到一定数量后 circuit会由close变成open

第十节  网关zuul使用

配置依赖 pom.xml

applicaioton.yml

配置注解

访问规则:网关地址:端口号/服务名称/接口路径和参数 

  例  订单服务  http://localhost:9000/order-service/api/v1/order/save?product_id=1&user_id=4

        商品服务  http://localhost:9000/product-service/api/v1/product/list

zuul自定义路由映射

踩坑1:product-service服务和order-service服务都映射到apigateway只有1个能生效????

原因:下面的把上面的覆盖了

解决方案:加一层路径 

访问地址也加一层 ,访问成功

http://localhost:9000/apigateway/order/api/v1/order/save?user_id=4&product_id=1

http://localhost:9000/apigateway/product/api/v1/product/list

踩坑2:HTTP请求头过滤不了

http请求前端传递cookie后端获取不了经过zuul网关时,zuul源码里有过滤掉敏感信息,过滤掉了3个词cookie,set-cookie,Authorization,不让进行传递

所以在配置文件里把请求头还原,让它过滤传递下去。

第十节 配置中心

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值