SpringCloud

初识Springcloud

  • 微服务是系统架构上的一种设计风格它的主旨是将一个原
    本独立的系统拆分成多个小型服务,这些小型服务都在各自
    独立的进程中运行,服务之间一般通过HTTP的RESTfuL
    API进行通信协作。
  • 被拆分成的每一个小型服务都围绕着系统中的某一项或些
    耦合度较高的业务功能进行构建,并且每个服务都维护着白
    身的数据存储、业务开发自动化测试案例以及独立部署航
    制。
  • Spring Cloud是一系列框架的有序集合。
  • Spring Cloud并没有重复制造轮子,它只是将目前各家公司开发的比较成熟、经得起实际考验的服务框架组合起来。
  • 通过Spring Boot风格进行再封装屏蔽掉了复杂的配置和实现原理,最终给开发者留出了一套简单易懂、易部署和易维护的分布式系统开发工具包。衡、断路器、数据监控等,都可以用Spring Boot的开发风格到一键启动和部署。
  • 它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、消息总线、负载均载
  • 微服务就是将项目的各个模块拆分为可独立运行、部署、测试的架构设计风格。
  • Spring公司将其他公司中微服务架构常用的组件整合起来,并使用SpringBoot简化其开发、配置。称Spring Cloud
  • Spring Cloud 与Dubbo都是实现微服务有效的工具。Dubbo性能更好,而Spring Cloud功能更全面。

SpringCloud服务治理

1. Eureka

  • Eureka是Netflix公司开源的一个服务注册与发现的组件。
  • Eureka和其他Netflix公司的服务组件(例负载均衡、熔断器、网关等)一起,被Spring Cloud社区整合为
    Spring-Cloud-Netflix模块。
  • Eureka包含两个组件: EurekaServer(注册中心)和Eureka Client(服务提供者、服务消费者)。

Eureka环境搭建

搭建步骤
  1. 搭建Provider和Consumer服务。

  2. 使用RestTemplate完成远程调用。

  3. 搭建Eureka Server服务。

  4. 改造Provider和Consumer称为Eureka Client。

  5. Consumer 服务通过从Eureka Server中抓取Provider
    地址完成远程调用

父工程依赖
<groupId>com.itheima</groupId>
<artifactId>spring_cloud_parent</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
    <module>eureka_provider</module>
    <module>eureka_consumer</module>
    <module>eureka_server</module>
</modules>

<!--引入springboot的依赖-->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
    <relativePath/>
</parent>


<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
</properties>
<!--引入springCloud依赖-->
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>${spring-cloud.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Server注册中心

pom文件

<dependencies>

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

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

代码

@SpringBootApplication
//启动Eureka服务
@EnableEurekaServer
public class EurekaApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaApplication.class, args);
    }
}

配置文件

server:
  port: 8761


#eureka
#eureka一共有四部分配置
  #dashboard:eureka的web控制台配置
  #server:eureka的服务端配置
  #cLient:eureka的客户端配置
  #instance:eureka的实例配置
eureka:
  instance:
    hostname: localhost #主机名

  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka #eureka暴露服务连接

    register-with-eureka: false #是否将自己的路径 注册到eureka 不需要 eurekaServer不需要注册 Client需要
    fetch-registry: false #是否需要从eureka中抓取路径 client/consumer才需要
#    healthcheck:
#      enabled: false
Provider生产端

pom文件

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

启动类

/**
 * 启动类
 */
@SpringBootApplication
@EnableEurekaClient//该注解 在新版本中可以省略
public class ProviderApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }

}

配置文件

server:
  port: 8081
eureka:
  instance:
     hostname: localhost #主机名

  client:
    service-url:
        defaultZone: http://localhost:8761/eureka #eureka服务注册
spring:
  application:
    name: eureka_provider #设置当前应用名称
Consumer消费端

pom文件

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

启动类

@SpringBootApplication
@EnableEurekaClient//该注解 在新版本中可以省略
@EnableDiscoveryClient//激活DiscoveryClient
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

配置文件

server:
  port: 8082
eureka:
  instance:
    hostname: localhost #主机名

  client:
    service-url:
      defaultZone: http://localhost:8761/eureka #eureka服务注册
spring:
    application:
      name: eureka_consumer #设置当前应用名称

服务调用代码

/**
 * 服务的调用方
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @GetMapping("/goods/{id}")
    public Goods findGoodsById(@PathVariable int id) {
        System.out.println("findGoodsById..id=" + id);
        /**
         * 远程调用Goods服务中的findOne接口
         * 使用RestTempLate
         * 1.定义BeanRestTempLate
         * 2.注入Bean
         * 3.调用方法
         */

        /*
            动态的从Eureka Server 中获取provider的ip端口
                1.注册DiscoveryClient 激活
                2.调用方法
         */
        List<ServiceInstance> instances = discoveryClient.getInstances("EUREKA_PROVIDER");
        if (instances == null && instances.size() == 0) {
            return null;
        }
        //获取实例对象
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();
        System.out.println(port);
        System.out.println(host);
        String url = "http://"+host+":"+port+"/goods/findOne/" + id;
        Goods goods = restTemplate.getForObject(url, Goods.class);
        return goods;

    }

}

Eureka配置详解

见笔记目录

Eureka高可用

搭建多服务,服务的名称保持一致

spring:
  application:
    name: eureka-server-ha

服务注册地址defaultZone相互注册

服务A

server:
  port: 8761
eureka:
  instance:
    hostname: eureka-server1 #主机名
  client:
    service-url:
      defaultZone: http://eureka-server1:8762/eureka #eureka暴露服务连接
    register-with-eureka: true #是否将自己的路径 注册到eureka 不需要 eurekaServer不需要注册 Client需要
    fetch-registry: true #是否需要从eureka中抓取路径 client/consumer才需要
#    healthcheck:
#      enabled: false
spring:
  application:
    name: eureka-server-ha

服务B

server:
  port: 8762

eureka:
  instance:
    hostname: eureka-server2 #主机名

  client:
    service-url:
      #集群相互注册
      defaultZone: http://eureka-server2:8761/eureka #eureka暴露服务连接

    register-with-eureka: true #是否将自己的路径 注册到eureka 不需要 eurekaServer不需要注册 Client需要
    fetch-registry: true #是否需要从eureka中抓取路径 client/consumer才需要

spring:
  application:
    name: eureka-server-ha

修改host文件 新增host识别地址

127.0.0.1       eureka-server2
127.0.0.1       eureka-server1

2. Consul

pom文件

<!--consul客户端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>-->
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>-->
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

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

配置文件

server:
  port: 9000
spring:
  cloud:
    consul:
      host: localhost #consul服务端ip
      port: 8500 #端口默认8500
      	discovery:
        	service-name: ${spring.application.name}
        	prefer-ip-address: true
        	
   application:
    name: consul_*

代码

代码同eureka

3. Nacos

pom文件

<!--nacos客户端-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    <version>0.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>com.alibaba.nacos</groupId>
    <artifactId>nacos-client</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

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

配置文件

server:
  port: 9000
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848 #nacos默认的端口是8848
  application:
    name: consul_consumer

启动nacos软件

4. Ribbon

Ribbon是Netflix提供的一个基于HTTP和TCP的客户端负载均衡工具。
Ribbon主要有两个功能:

  1. 简化远程调用

  2. 负载均衡

简化远程调用

在配置类中添加**@LoadBalanced**

在使用restTemplate发起请求时,需要定义url时,host:port可以替换为服务提供方的应用名称

Ribbon的负载均衡策略

  • 随机:RandomRule
    • 轮询:RoundRobinRule
    • 最小并发:BestAvailableRule
    • 过滤: AvailabilityFilteringRule
    • 响应时间: WeightedResponseTimeRule
    • 轮询重试: RetryRule
    • 性能可用性:ZoneAvoidanceRule
配置Ribbon负载均衡

编码:

  1. 编写规则类,返回IRULE接口对应的实现规则类

    @Configuration
    public class MyRule {
        @Bean
        public IRule rule(){
            return new RandomRule();
        }
    }
    
  2. 在启动类配置注解

    @RibbonClient(name = "服务名称",configuration = 规则类class文件)
    

配置:

  1. 服务配置文件添加配置

    EUREKA-PROVIDER: #服务名称
      ribbon:
        NFloadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule #规则类全包名
    

5. Feign声明式服务调用

概述:Fegin是一个声明式的REST客户端,它用了基于接口的注解方式,很方便的实现客户端的配置

/**
 * feign声明式接口.发起远程调用
 * 1.定义接口
 * 2.接口上添加注解@Feignclient,设置vaLue属性为服务提供者的应用名称
 * 3.编写调用接口,接口的声明规则和提供方接口保持—致。
 * 4. 注入接口对象,调用接口方法完成调用
 */
@FeignClient(value = "feign-provider")
public interface GoodsFeignClient {
    @GetMapping("/goods/findOne/{id}")
    public Goods findOneById(@PathVariable int id);
}

接口访问地址和映射路径应该和服务提供方保持一致

Feign超时配置

ribbon: #全局配置如果需要单独配置则需要加服务
	ConnectTimeout: 1000 #毫秒
    ReadTimeout: 1000 #毫秒

Feign日志记录

配置文件

logging: 
	level: 
		com.itheima: debug #限定日志记录包

配置类

@Configuration
public class FeignLogConfig {
    @Bean
    public Logger.Level level() {
        return Logger.Level.FULL;
    }
}

在声明式服务调用接口加上配置configuration参数

@FeignClient(value = "feign-provider" ,configuration = FeignLogConfig.class)
public interface GoodsFeignClient {
    @GetMapping("/goods/findOne/{id}")
    public Goods findOneById(@PathVariable int id);
}

6. Hystrix熔断器

  • Hystix是Netflix开源的一个延迟和容错库,用于隔离访问远程服务、第三方库,防止出现级联失败(雪崩)。

Hystrix功能

隔离
  • 线程池隔离
  • 信号量隔壁
降级
服务端降级
  1. 在服务提供方,引入hystrix依赖

    <dependencies>
            <!--spring boot web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
            <!-- eureka-client -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
        
            <!-- hystrix -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
            </dependency>
        </dependencies>
    
  2. 定义降级方法

    降级方法需要与原方法(参数,返回值)一致

    public Goods findOne_FallBack(int id) {
        Goods goods = new Goods();
        goods.setTitle("降级方案");
        return goods;
    }
    
  3. 使用@HystrixCommand注解配置降级方法

    @HystrixCommand(fallbackMethod = "findOne_FallBack", commandProperties = {
    		//配置超时时间参数 
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "2500")
    
    })
    

    相关配置参数在HystrixCommandProperties类中查询配置

  4. 在启动类上开启Hystrix功能:@EnableCircuitBreaker

    @SpringBootApplication
    @EnableCircuitBreaker //开启熔断器
    public class ProviderApp {
        public static void main(String[] args) {
            SpringApplication.run(ProviderApp.class,args);
        }
    }
    
消费端降级
  1. 引入Hystrix依赖

    <dependencies>
    
            <!--spring boot web-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
    
            <!-- eureka-client -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
    
            <!--feign-->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-openfeign</artifactId>
            </dependency>
            <dependency>
                <groupId>com.netflix.hystrix</groupId>
                <artifactId>hystrix-metrics-event-stream</artifactId>
                <version>1.5.18</version>
                <scope>compile</scope>
            </dependency>
            
        </dependencies>
    
    1. 定义降级方案

      消费端的降级方案 接口声明fallback降级方案

      在Feign的调用接口实现一个实现类即为降级方案

      @FeignClient(value = "HYSTRIX-PROVIDER",fallback = GoodsFeignClientFallBackImpl.class)
      @Component
      public interface GoodsFeignClient {
      
      
          @GetMapping("/goods/findOne/{id}")
          public Goods findGoodsById(@PathVariable("id") int id);
      
      }
      //降级实现类 
      /**
       * Feign客户端的降级处理类
       * 1.定义类实现Feign客户端接口
       * 2.使用@component注解将该类的Bean加入SpringIoc容器
       */
      @Component
      public class GoodsFeignClientFallBackImpl implements GoodsFeignClient {
          @Override
          public Goods findGoodsById(int id) {
              Goods goods = new Goods();
              goods.setTitle("消费降级方案");
              return goods;
          }
      }
      
      
熔断

Hystrix熔断机制,用于监控微服务调用情况,当失败的情况达到预定的阈值(5秒失败20次),会打开断路器,拒绝所有请求,知道服务恢复正常为止

image-20201102230608324

一般是自动开启断路器的状态

可以手动配置一个策略

circuitBreaker.sleepWindowInMilliseconds //失败时间
circuitBreaker.requestVolumeThreshold //失败次数
circuitBreaker.errorThresholdPercentage //失败百分比
Hystrix熔断监控

提供Hystrix-dashboard功能,用于实时监控微服务运行状态

熔断聚合监控Turbine搭建查询资料Turbine搭建步骤

限流

7. Gateway网关

概述:网关旨在为微服务架构提供一种简单而有效的统一的API路由管理方式。

网关就是系统的入口,封装了应用程序的内部结构,为客户端提供统一服务,一些与业务本身功能无关的公共逻辑可以在这里实现,诸如认证、鉴权、监控、缓存、负载均衡、流量管控、路由转发等

静态路由,静态的配置网关

  cloud:
    #网关规则
    gateway:
      #路由规则
      routes: #集合
        #id:唯一标识
        #uri :转发路径
        #predicate
        - id: gateway-provider
          uri: http://localhost:8001/ #静态路由
          # uri: lb://GATEWAY-PROVIDER
          predicates:
            - Path=/goods/**

动态路由

动态路由之后gateway回去eureka注册中心获取服务的名称获取相应的地址

  cloud:
    #网关规则
    gateway:
      #路由规则
      routes: #集合
        #id:唯一标识
        #uri :转发路径
        #predicate
        - id: gateway-provider
#          uri: http://localhost:8001/ 静态路由
          uri: lb://GATEWAY-PROVIDER #动态路由
          predicates:
            - Path=/goods/**

微服务名称配置

在实际的开发中许多api可能接口的名称有所相同使用

discovery:
  locator:
    enabled: true #开启微服务发现
    lower-case-service-id: true #转小写

过滤器

  • Gateway支持过滤器功能,对请求或响应进行拦截,完成一些通用操作。
  • Gateway提供两种过滤器方式:“pre”和“post"
    pre过滤器,在转发之前执行,可以做参数校验、权限校验、流量监控、日志输出、协议转换等。
  • post过滤器,在响应之前执行,可以做响应内容、响应头的修改,日志的输出,流量监控等。
  • Gateway还提供了两种类型过滤器
    • GatewayFilter:局部过滤器,针对单个路由-
    • GlobalFiliter :全局过滤器,针对所有路由

Gateway提供大量的内置过滤器工厂Gateway的过滤器工厂

8. Config分布式配置中心

Spring Cloud Config解决了在分布式场景下多环境配置文件的统一管理和维护。

搭建远程仓库gitee

https://gitee.com/lcy1225/java-config.git

搭建config-server服务端

pom文件

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>

application.yml文件

server:
  port: 8888

spring:
  application:
    name: config-server
    #配置git的远程地址
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/lcy1225/java-config.git #远程仓库地址
        default-label: master #分支配置

启动类

@SpringBootApplication
@EnableConfigServer//启动config-server功能
public class ConfigServerApp {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApp.class,args);
    }
}

搭建config-client客户端

pom文件

<dependencies>

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

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


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

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

application.yml eureka文件配置

server:
  port: 8001

eureka:
   client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: config-provider

bootstrap.yml文件

spring:
  cloud:
    config:
      #uri: localhost:8888 默认8888本地端口获取远程配置
      name: config #远程配置文件名
      profile: dev  #远程配置环境
      label: master

config自动刷新服务

自动刷新配置

management:
  endpoints:
    web:
      exposure:
        include: refresh

config集成eureka

config-server服务端配置注册中心地址

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

config-provider消费提供端提供注册中心地址拉取地址

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka

开启消费端发现远程配置中心地址功能

#从注册中心寻找config-server 默认是configserver
discovery:
  enabled: true
  service-id: config-server

启用eureka注解

@EnableEurekaClient

9. Bus消息总线

概述:

  • Spring Cloud Bus是用轻量的消息中间件将分布式的节点连接起来,可以用于广播配置文件更改或者服务的监控管理。关键的思想就是,消息总线可以为微服务做监控,也可以实现应用程序之间相通信。
  • Sprina Cloud Bus 可选的消息中间件包括RabbitMQ和Kafka.

springcloud2.0之后刷新配置接口改为/monitor

server端

pom文件

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

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <!--bus-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-bus-amqp</artifactId>
    </dependency>
    <!--monitor -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-monitor</artifactId>
    </dependency>
</dependencies>

yml

server:
  port: 8888

spring:
  application:
    name: config-server
    #配置git的远程地址
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/lcy1225/java-config.git

        default-label: master #分支配置
    #配置rabbitmq信息
  rabbitmq:
    host: 47.96.250.191
    port: 5672
    username: root
    password: root
    virtual-host: /
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
#暴露bus的端点
management:
  endpoints:
    web:
      exposure:
        include: '*'

consumer端

pom文件

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

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


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

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

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

<!-- bus -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

bootstrap yml文件

spring:
  cloud:
    config:
      name: config #远程配置文件名
      profile: dev  #远程配置环境
      label: master
      #从注册中心寻找config-server 默认是configserver
      discovery:
        enabled: true
        service-id: config-server
    #bus开启git远程webhook地址更新
    bus:
      enabled: true
      id: ${spring.application.name}:${spring.cloud.config.profile}:${random.value}
  #配置rabbitmq信息
  rabbitmq:
    host: 47.96.250.191
    port: 5672
    username: root
    password: root
    virtual-host: /
#暴露bus的端点
management:
  endpoints:
    web:
      exposure:
        include: '*'

application文件

server:
  port: 8001

eureka:
   client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: config-provider

使用@RefreshScope注解加载需要热刷新控制器或者bean上

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

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;
	//远程配置信息
    @Value("${helloworld}")
    private String info;
    /**
     * 降级:
     *  1. 出现异常
     *  2. 服务调用超时
     *      * 默认1s超时
     *
     *  @HystrixCommand(fallbackMethod = "findOne_fallback")
     *      fallbackMethod:指定降级后调用的方法名称
     */

    @RequestMapping("/findOne/{id}")
    @HystrixCommand(fallbackMethod = "findOne_fallback")
    public Goods findOne(@PathVariable("id") int id){
        Goods goods = goodsService.findOne(id);
		//将端口号,远程配置信息,设置到了 商品标题上
        goods.setTitle(goods.getTitle() + ":" + port+":"+info);
       
        return goods;
    }
    /**
     * 定义降级方法:
     *  1. 方法的返回值需要和原方法一样
     *  2. 方法的参数需要和原方法一样
     */
    public Goods findOne_fallback(int id){
        Goods goods = new Goods();
        goods.setTitle("降级了~~~");

        return goods;
    }

}

:springcloud2.0版本之后 bus-refresh接口热刷新在git的webhook上不支持自调用 使用monitor接口支持热刷新机制 需要导入monitor依赖

10. stream消息驱动

概述:stream是一个构建消息驱动微服务应用的框架。

作用:Stream解决了开发人员无感知的使用消息中间件的问题,因为Stream对消息中间件的进一步封装,可以做到代码层面对中间件的无感知,甚至于动态的切换中间件,使得微服务开发的高度解耦,服务可以关注更多自己的业务流程。

Stream组件

image-20201112213310944

  • Spring Cloud Stream构建的应用程序与消息中间件之间是通过绑定器Binder相关联的。绑定器对于应用程序而言起到了隔离作用,它使得不同消息中间件的实现细节对应用程序来说是透明的。
  • binding是我们通过配置把应用和spring cloud stream的binder绑定在一起
  • output:发送消息Channel,内置Source接口
  • input:接收消息Channel,内置Sink接口

11.Sleuth+Zipkin链路追踪

  • Spring Cloud Sleuth其实是一个工具,它在整个分布式系统中能跟踪一个用户请求的过程,捕获这些跟踪数据,就能构建微服务的整个调用链的视图,这是调试和监控微服务的关键工具。
  • Zipkin是 Twitter的一个开源项目,它致力于收集服务的定时数据,以解决微服务架构中的延迟问题,包括数据的收集存储,杳找,和展示

pom文件

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

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


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



 <!--sleuth-zipkin-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-sleuth</artifactId>
</dependency>

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

yml

zipkin:
  base-url: http://localhost:9411/  # 设置zipkin的服务端路径

sleuth:
  sampler:
    probability: 1 # 采集率 默认 0.1 百分之十。

开启ZipkinServer服务

上一篇 下一篇