1.springcloud 和 springboot 版本对应关系

Spring Cloud 和 boot 对应版本

更详细的技术选型(版本对应关系)

https://start.spring.io/actuator/info

Gitee项目传送门

一、服务注册中心

CAP理论

Consistency: 一致性

Availability: 可用性

Partition tolerance: 分区容错性

1.1 Euraka(AP)

  • 关键注解:

@EnableEurekaServer

@EnableEurekaClient(可省略不写)

  • 依赖
<!--服务端-->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<!--客户端-->
<dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
  • 配置
# 1.服务端配置
server:
  port: 7001
eureka:
  instance:
    hostname: localhost
  client:
    register-with-eureka: false  #是否自我注册
    fetch-registry: false  #是否从注册中心获取注册的服务信息
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ 
  server:
    enable-self-preservation: false  #禁止eureka自我保护

-------手动分割---------

# 2.客户端配置
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      default:http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  instance:
    instance-id: payment8001  #instance重命名,默认为 PC名:APPNAME
    prefer-ip-address: true #访问路径可以显示IP地址
    lease-renewal-interval-in-seconds: 10   #客户端向服务端发送心跳的时间间隔,默认30s
    lease-expiration-duration-in-seconds: 10  #服务端在收到最后一次心跳后的等待时间上限,默认90s 后剔除服务

1.2 Zookeeper(CP)

  • 安装
wget wget http://mirrors.hust.edu.cn/apache/zookeeper/zookeeper-3.4.13/zookeeper-3.4.13.tar.gz

tar -zxvf zookeeper-3.4.13.tar.gz

cd /usr/local/zookeeper

#启动
./zkServer.sh
  • 依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.zookeeper</groupId>
                    <artifactId>zookeeper</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.4.14</version>
        </dependency>
  • 配置
spring:
  application:
    name: cloud-payment-service
  cloud:
    zookeeper:
      connect-string: 192.168.101.102:2181

1.3 Consul(CP)

由Go语言开发,是一套开源的分布式服务发现和配置管理系统。

  • 安装
wget https://releases.hashicorp.com/consul/1.12.0/consul_1.12.0_linux_amd64.zip --no-check-certificate
unzip consul_1.12.0_linux_amd64.zip
./consul
./consul agent -dev -ui -node=consul-dev -client=192.168.x.x
  • 依赖
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
  • 配置
spring:
  application:
    name: consul-provider-payment
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}
        instance-id: ${spring.application.name}
        port: ${server.port}
        ip-address: ${spring.cloud.consul.discovery.instance-id}

1.4 Nacos

二、服务调用

2.1 Ribbon

  • 什么是Ribbon?

客户端负载均衡工具。

当我们启动 orderservice,第一次访问时,时间消耗会大很多,这是因为 Ribbon 懒加载的机制。

  • Ribbon核心组件IRule,有自带的负载均衡算法

Ribbon的自定义配置类,不能放在@ComponentScan所扫描的当前包以及子包下(也就是说要和使用@SpringBootApplication的类的父文件夹同级。),否则自定义的配置类就会被所有的Ribbon客户端共享,达不到特殊化定制的目的了。

  • 手写轮询算法(扩展)
/**
 * @author o_o
 * @date 2022-07-29
 */
@Component
public class LoadBalancerImpl implements LoadBalancer {

    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(index);
    }

    //CAS
    private int getAndIncrement() {
        int current;
        int next;
        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!atomicInteger.compareAndSet(current, next));
        System.out.println("********** next = " + next);
        return next;
    }
}

2.2 Openfeign

  • 什么是openfeign? 接口+注解

Feign是一个声明式webservice客户端,使用feign能让编写webservice客户端更加简单。Feign可以与Eureka和Ribbon组合使用支持负载均衡。

  • 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • openfeign的使用 ,注解+接口
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentService {

    /**
     * feign 实现远程调用
     *
     * @return string
     */
    @GetMapping("/payment/feign")
    String feign();

}
  • openfeign超时控制
# 设置feign 客户端超时时间(openFeign默认支持ribbon)
ribbon:
  # 两端建立连接的时间
  ReadTimeout: 3000
  # 从服务器读取资源的时间
  ConnectTimeout: 5000
  • openfeign日志功能
logging:
  level:
    com.kk.feign.service.PaymentService: debug
  • 配置类
@Configuration
public class FeignConfig {

    /**
     * NONE: 默认的,不显示任何日志
     * BASIC:仅记录请求方法、URL、响应状态码以及执行时间
     * HEADERS:除了BASIC中定义的信息以外,还有请求和响应的头信息
     * FULL: 除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据
     * @return level
     */
    @Bean
    Logger.Level feignLogger() {
        return Logger.Level.FULL;
    }
}

三、服务降级/熔断/限流

3.1 Hystrix

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

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

什么是Hystrix ?能干嘛?

断路器。可以做服务降级、熔断、限流,以及接近实时的监控。

3.1.1服务降级 fallback

当服务不可用(异常或超时),不让客户端一直等待,并立即返回一个友好提示。

场景:程序异常、超时、服务熔断触发服务降级、线程池/信号量打满也会导致服务降级。

@EnableCircuitBreaker

  • 单个的服务降级

@HystrixCommand(fallbackMethod = "pocketBottom", commandProperties = { @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000") })

  • 全局的服务降级

@HystrixCommand

@DefaultProperties(defaultFallback = "globalFallbackMethod")

  • 调用的服务挂了

先写一个feign接口的实现类

@FeignClient(value = "hystrix-payment-service", fallback = PaymentFallbackServiceImpl.class)

3.1.2服务熔断 break

  • 服务降级–>服务熔断–>恢复调用链路

当服务挂了,直接拒绝访问,触发服务降级返回友好提示。类似保险丝。

@HystrixCommand(fallbackMethod = "hystrixCircuitBreakerFallback", commandProperties = { //是否开启断路器 @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ENABLED, value = "true"), //请求次数 @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_REQUEST_VOLUME_THRESHOLD, value = "10"), //时间窗口期 @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_SLEEP_WINDOW_IN_MILLISECONDS, value = "10000"), //失败率到达多少跳闸 @HystrixProperty(name = HystrixPropertiesManager.CIRCUIT_BREAKER_ERROR_THRESHOLD_PERCENTAGE, value = "60"), })

3.1.3服务限流 flowlimit

秒杀高并发等操作,严禁全部请求打过来,大家排队一秒N个,有序进行。

四、服务网关

4.1 Spring Cloud Gateway

  • 什么是Gateway??

Gateway,API网关服务,是zuul 1.x的代替版。旨在提供一种简单而有效的方式来对API进行路由,以及提供一些强大的过滤器功能,例如:熔断、限流、重试等。为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式的通信框架Netty。

  • 依赖
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
  • yml
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
            default-filters:
              - DedupeResponseHeader=Vary Access-Control-Allow-Origin Access-Control-Allow-Credentials, RETAIN_FIRST

      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名进行路由

      routes:
        - id: pament_rout1            # 路由的唯一标识
#          uri: http://localhost  # 如果断言成功,将要转发去的地址
          uri: lb://CLOUD-CONSUMER-FEIGN-ORDER  # 如果断言成功,将要转发去的地址
          predicates:
            - Path=/order/**     # 断言,路径匹配的进行路由

        - id: pament_rout2
#          uri: http://localhost  # 如果断言成功,将要转发去的地址
          uri: lb://CLOUD-CONSUMER-FEIGN-ORDER  # 如果断言成功,将要转发去的地址          order: 0
          predicates:
            - Path=/feign/circuitBreak/**
#            - Before=2021-08-25T12:53:46.101+08:00[Asia/Shanghai] #匹配这个时间之前的请求
#            - After=2021-08-25T12:53:46.101+08:00[Asia/Shanghai]  #匹配这个时间之后的请求
#            - Between=2021-08-25T12:53:46.101+08:00[Asia/Shanghai],2021-09-25T12:53:46.101+08:00[Asia/Shanghai] #匹配这个两个时间的请求
#            - Cookie=name,wwzzqq
#            - Header=X-Request-Id,\d+  #请求头要有 X-Request-Id 属性并且值为整数的正则表达式
#            - Host=shangguigu.com
#            - Method=GET  #请求方式是 GET
#            - Query=username,\d+ #要有参数名 username 并且值还要是证书才能路由


eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    service-url:
     defaultZone: http://eureka7001.com:7001/eureka
    register-with-eureka: true
    fetch-registry: true

五、服务配置中心

5.1 SpringCloud Config Center

  • 什么是配置中心?

SpringCloud Config Center 为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同微服务应用的所有环境提供了一个中心化的外部配置。

服务端配置

<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-config-server</artifactId>
</dependency>
server:
  port: 3344

spring:
  application:
    name: config-center
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/kk-dad/springcloud-config.git
          search-paths:
            - springcloud-config
      label: master

eureka:
  client:
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka
    register-with-eureka: true
    fetch-registry: true

客户端配置

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

application.yml 改为 bootstrap.yml,这是关键的一步不然启动会报错!!

server:
  port: 80

spring:
  application:
    name: cloud-consumer-feign-order-config-client
  cloud:
    config:
      label: master
      name: application
      profile: dev
      uri: http://localhost:3344


eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
    #客户端向服务端发送心跳的时间间隔,默认30s
    lease-renewal-interval-in-seconds: 10
    #服务端在收到最后一次心跳后的等待时间上限,默认90s 后剔除服务
    lease-expiration-duration-in-seconds: 10
 

六、消息总线

  • 什么是消息总线?

在微服务架构体系中,通常会使用轻量级的消息代理来构建一个共用的消息主题,并让系统中所有微服务实例都连接上来。由于该主题中产生的消息会被所有实例监听和消费,所以会被称为消息总线。

  • 基本原理

config client 实例都监听MQ中的同一个topic(默认是springcloud bus)。当一个服务刷新数据的时候,他会把这个消息放入到topic中,这样其他监听同一个topic的服务就得到通知,然后更新自身的配置信息。

  • spring cloud bus?

springcloud bus是用来将分布式系统的节点与轻量级消息系统链接起来的框架,它整合了Java的事件处理机制和消息中间件的功能。springcloud bus 目前支持 RabbitMQ 和 Kafka。

Spring cloud Bus 配合 Spring cloud config center 可以实现配置的动态刷新。

原文地址:http://www.cnblogs.com/qqkkOvO/p/16910122.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性