乐趣区

关于springcloud:SpringCloudSpringCloudAlibaba学习笔记

服务注册核心

eureka

ap 高可用 分布式容错

<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>
eureka:
  instance:
    hostname: eureka7003.com #eureka 服务端的实例名称
    instance-id: payment8001 
    prefer-ip-address: true
  client:
    register-with-eureka: false     #false 示意不向注册核心注册本人。fetch-registry: false     #false 示意本人端就是注册核心,我的职责就是保护服务实例,并不需要去检索服务
    service-url:
      #集群指向其它 eureka
      #defaultZone: http://eureka7002.com:7002/eureka/
      #单机就是 7001 本人
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
    #server:
    #敞开自我爱护机制,保障不可用服务被及时踢除
    #enable-self-preservation: false
    #eviction-interval-timer-in-ms: 2000

Ribbon 启用负载平衡

@EnableEurekaServer
@EnableDiscoveryClient

@LoadBalanced
public RestTemplate getTemp() {return new RestTemplate();
}

zookepper

cp 强统一 分布式容错

<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.6.1</version>
</dependency>
spring:
  application:
    name: cloud-zoo-consumer-order
  cloud:
    zookeeper:
      connect-string: 192.168.10.58:2181
@SpringBootApplication
@EnableDiscoveryClient

consul

cp 强统一 分布式容错

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-consul-discovery</artifactId>
</dependency>
spring:
  application:
    name: consul-payment-provider
  cloud:
    consul:
      host: 192.168.10.58
      port: 8500
      discovery:
        service-name: ${spring.application.name}
@SpringBootApplication
@EnableDiscoveryClient

服务调用负载平衡

Ribbon

Ribbon 切换 负载规定

  1. 在 springboot 包扫描外层建设 配置
@Configuration
public class Myrule {
    @Bean
    public IRule initRule() {return new RandomRule();
    }
}
  1. 启动类给指定服务加载随机办法
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = Myrule.class)

OpenFeign

  1. 增加 maven 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. 启动类启用 Feign
@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
@EnableFeignClients
  1. 新建接口 并注册 Feign 信息
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")  // 提供方服务名
public interface Service {@GetMapping(value = "/payment/get/{id}")
    Response<Payment> getPaymentById(@PathVariable("id") Long id);
}
  1. 提供方接口演示
@GetMapping(value = "/payment/get/{id}")
public Response<Payment> getPaymentById(@PathVariable("id") Long id) {Payment payment = paymentService.getPaymentById(id);

    if (payment != null) {return Result.success(200, "查问胜利,serverPort:" + serverPort, payment);
    } else {return Result.success(444, "没有对应记录, 查问 ID:" + id, null);
    }
}

OpenFeign 超时设置

ribbon:
#指的是建设连贯所用的工夫,实用于网络情况失常的状况下, 两端连贯所用的工夫
  ReadTimeout: 5000
#指的是建设连贯后从服务器读取到可用资源所用的工夫
  ConnectTimeout: 5000

OpenFeign 日志打印性能

  1. 配置 Openfeign 日志级别
@Configuration
public class FeignLogConfig {
    @Bean
    public Logger.Level getLevel() {return Logger.Level.FULL;}
}
  1. yml 我的项目配置文件中, 给指定 Feign interface 配置日志级别
logging:
  level:
    ml.ytooo.feignservice.Service: debug

服务治理

  • 服务降级 出险异样时, 返回敌对提醒, 避免程序异样或者阻塞
  • 服务熔断 保险丝, 当超出服务承载能力时, 返回提醒, 拒绝请求
  • 服务限流 闸门, 配置服务承载能力

Hystrix

服务降级
当服务解决超时或者运行异样时, 启动备选计划返回给调用者预期后果

主办法

@EnableCircuitBreaker

须要降级解决的程序

其中

  • paymentInfo_TimeOut 为预计超时程序
  • paymentInfo_TimeOut_Handler 为超时备选计划
@HystrixCommand(fallbackMethod = "paymentInfo_TimeOut_Handler", commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
})
public String paymentInfo_TimeOut(Integer id) {

    int time = 5;
    try {TimeUnit.MILLISECONDS.sleep(time * 1000); } catch (InterruptedException e) {e.printStackTrace(); }
    return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut,id:" + id + "\t" + "O(∩_∩)O 哈哈~" + "耗时 (秒):" + time;
}

public String paymentInfo_TimeOut_Handler(Integer id) {return "线程池:" + Thread.currentThread().getName() + "paymentInfo_TimeOut_Handler,id:" + id + "\t" + "o(╥﹏╥)o";
}
全局降级解决

配置 defaultFallback 的走本人的降级办法, 未配置的走 默认 @DefaultProperties 指定的降级办法

@RestController
@Slf4j
@DefaultProperties(defaultFallback = "globle",commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1500")
})
public class Controller {
    @HystrixCommand
    @GetMapping("/timeout/{id}")
    public String paymentInfo_TimeOut(@PathVariable("id") Integer id) {String result = feignService.paymentInfo_TimeOut(id);
        log.info("*****result:" + result);
        return result;
    }
    public String globle() {return "全局";}
}
通过 OpenFeign 配置其提供方全局降级配置
  1. 新增 feign 调用接口的实现类 FeignServiceImpl, 实现全副办法并做降级解决
@Service
public class FeignServiceImpl implements FeignService {
    @Override
    public String paymentInfo_OK(Integer id) {return "降级 -- paymentInfo_OK";}
    @Override
    public String paymentInfo_TimeOut(Integer id) {return "降级 -- paymentInfo_TimeOut";}
}
  1. feign 调用接口增加注解
@FeignClient(value = "CLOUD-PROVIDER-HYSTYRIX-PAYMENT",fallback = FeignServiceImpl.class)
服务熔断
  • 服务过载时, 回绝连贯申请间接调用降级办法, 返回异样
  • 申请下降时, 缓缓复原该服务拜访, 中转完全恢复

配置服务的熔断:

一下配置在 10s 内 ,10 次申请有 60% 失败, 则熔断

HystrixProperty 配置位于 HystrixCommandProperties.class 类中

//===== 服务熔断
@HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = { //
        @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),// 是否开启断路器
        @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),// 申请次数
        @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"), // 工夫窗口期
        @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),// 失败率达到多少百分百后跳闸
})
public String paymentCircuitBreaker(@PathVariable("id") Integer id)
{if(id < 0)
    {throw new RuntimeException("******id 不能正数");
    }
    String serialNumber = IdUtil.simpleUUID();

    return Thread.currentThread().getName()+"\t"+"调用胜利,流水号:" + serialNumber;
}
public String paymentCircuitBreaker_fallback(@PathVariable("id") Integer id) // 熔断后降级办法
{return "id 不能正数,请稍后再试,/( ㄒ o ㄒ)/~~   id:" +id;
}

成果: 当间断应用 -100 申请时, 返回 “id 不能正数 ”, 应用 100 申请也返回 “id 不能正数 ” , 持续间断应用 100 申请, 服务缓缓复原

服务限流

应用 springcloud 阿里巴巴 sentinel 代替

网关

Gateway

Gateway 我的项目配置

  1. 增加 maven 依赖
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  1. 移除以下依赖
<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>
  1. yml 配置 (后续移步配置核心)
spring:
  application:
    name: cloud-gateaway-gateaway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_get
        #   uri: http://127.0.0.1:8001    #繁多节点
          uri : lb://CLOUD-PAYMENT-SERVICE  /# 启用 注册核心集群
          predicates:
            - Path=/payment/get/**
  1. 注册进 Eureka 注册核心

Gateway 动静路由

  1. 开启 网关发现注册核心服务
spring:
  application:
    name: cloud-gateaway-gateaway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true

Gateway 断言

断言是判断转发申请的条件

predicates:
 - After=2020-02-21T15:51:37.485+08:00[Asia/Shanghai]
  1. After,Before,Between 配置转发失效工夫
public static void main(String[] args) {ZonedDateTime now = ZonedDateTime.now();
    System.out.println(now);
}
// 2020-08-24T14:23:57.171+08:00[Asia/Shanghai]
  1. Cookie 申请需携带指定 Cookie 才能够拜访
predicates:
  - Cookie=name,ytooo   # key,value
  1. Header ≈ Cookie
predicates:
  - Header=name,ytooo   # key,value

Gateway 过滤器

  1. (默认过滤器) 官网提供一系列过滤器, 供咱们 在申请转发之前, 对申请进行加工解决
filters:
  - AddRequestParamter=rowid,1024
  1. 自定义过滤器

自定义全局过滤器

@Component
@Slf4j
public class GatewayLogFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("===================== 进入全局过滤器 =====================");
        String name = exchange.getRequest().getQueryParams().getFirst("name");
        if (null == name) {exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {return 0;}
}

分布式配置核心, 音讯总线

分布式配置核心 SpringCloud Config

服务端配置

  1. 简历 git 仓库 https://github.com/youdmeng/c…
  2. 引入 maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

3. 启动类使配置失效

@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigMain3344 {public static void main(String[] args) {SpringApplication.run(ConfigMain3344.class, args);
    }
}
  1. 配置 配置文件
spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://github.com/youdmeng/cloud-config
          search-paths:
            - cloud-config
      label: master
  1. 申请拜访 : http://127.0.0.1:3344/master/config-dev.yml

客户端配置

  1. 引入 maven
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-client</artifactId>
</dependency>
  1. 配置 配置文件
spring:
  application:
    name: cloud-condig-client
  cloud:
    config:
      label: master  # 分支
      name: config # 配置文件名称
      profile: dev   # 版本
      uri: http://127.0.0.1:3344 # config 服务端地址 

手动刷新客户端配置

不倡议应用

音讯总线 Bus

设计逻辑

应用音讯总线触发服务端的 bus/refresh 端点, 刷新所有客户端 config 配置

初始条件

客户端, 服务端都须要实现 Springcloud Config 性能

服务端配置

  1. 引入 maven 依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  1. 配置文件中配置音讯队列信息
# 配置音讯队列
rabbitmq:
  host: 192.168.10.58
  port: 5672
  username: ytooo
  password: ytooo
  1. 配置文件中配置 BUS 总线裸露信息
# 配置 bus 裸露端点
management:
  endpoints:
    web:
      exposure:
        include: "bus-refresh"
  1. 配置文件预览
server:
  port: 3344
spring:
  application:
    name: cloud-config-center
  cloud:
    config:
      server:
        git:
          uri: https://github.com/youdmeng/cloud-config
          search-paths:
            - cloud-config
      label: master
  # 配置音讯队列
  rabbitmq:
    host: 192.168.10.58
    port: 5672
    username: ytooo
    password: ytooo
eureka:
  instance:
    prefer-ip-address: true
    instance-id: cloud-config-center-3344
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/ #,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/
# 配置 bus 裸露端点
management:
  endpoints:
    web:
      exposure:
        include: "bus-refresh"

客户端配置

  1. 引入 maven 依赖
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
  1. 配置文件中配置音讯队列信息
# 配置音讯队列
rabbitmq:
  host: 192.168.10.58
  port: 5672
  username: ytooo
  password: ytooo
  1. 配置裸露端点
# 配置裸露端点
management:
  endpoints:
    web:
      exposure:
        include: "*"
  1. 调用配置类增加 @RefreshScope

@RestController
@RefreshScope
public class Controller {@Value("${config.info}")
    private String configInfo;
    @GetMapping(value = "/test")
    public String test() {return configInfo;}
}

刷新配置

POST 申请 config 服务端 http://127.0.0.1:3344/actuator/bus-refresh

刷新胜利

定点告诉

POST 申请 config 服务端 http://127.0.0.1:3344/actuator/bus-refresh/{destination}

destination: 注册核心服务名称: 端口号

????: http://127.0.0.1:3344/actuator/bus-refresh/cloud-condig-client:3366

音讯驱动

音讯驱动, 对立各种消息中间件中的差别, 提供对立简略的调用形式, 屏蔽消息中间件具体调用实现

退出移动版