SpringCloud -Netflix 总结·

springcloud 核心组件

image
Spring Cloud是一系列框架的有序集合。它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册、配置中心、智能路由、消息总线、负载均衡、断路器、数据监控等,都可以用Spring Boot的开发风格做到一键启动和部署

Spring Cloud Config
集中配置管理工具,分布式系统中统一的外部配置管理,默认使用Git来存储配置,可以支持客户端配置的刷新及加密、解密操作。

Spring Cloud Bus
用于传播集群状态变化的消息总线,使用轻量级消息代理链接分布式系统中的节点,可以用来动态刷新集群中的服务配置。

Spring Cloud Consul
基于Hashicorp Consul的服务治理组件。

Spring Cloud Security
安全工具包,对Zuul代理中的负载均衡OAuth2客户端及登录认证进行支持。

Spring Cloud Sleuth
Spring Cloud应用程序的分布式请求链路跟踪,支持使用Zipkin、HTrace和基于日志(例如ELK)的跟踪。

Spring Cloud Stream
轻量级事件驱动微服务框架,可以使用简单的声明式模型来发送及接收消息,主要实现为Apache Kafka及RabbitMQ。

Spring Cloud Task
用于快速构建短暂、有限数据处理任务的微服务框架,用于向应用中添加功能性和非功能性的特性。

Spring Cloud Zookeeper
基于Apache Zookeeper的服务治理组件。

Spring Cloud Gateway
API网关组件,对请求提供路由及过滤功能。

Spring Cloud OpenFeign
基于Ribbon和Hystrix的声明式服务调用组件,可以动态创建基于Spring MVC注解的接口实现用于服务调用,在Spring Cloud 2.0中已经取代Feign成为了一等公民。

Spring Cloud Netflix

  • Netflix OSS 开源组件集成,包括Eureka、Hystrix、Ribbon、Feign、Zuul等核心组件。

  • Eureka:服务治理组件,包括服务端的注册中心和客户端的服务发现机制;

  • Ribbon:负载均衡的服务调用组件,具有多种负载均衡调用策略;

  • Hystrix:服务容错组件,实现了断路器模式,为依赖服务的出错和延迟提供了容错能力;

  • Feign:基于Ribbon和Hystrix的声明式服务调用组件;

  • Zuul:API网关组件,对请求提供路由及过滤功能。

Eureka 注册中心

  • 集群
  • VS Zookeeper
  • CAP原则CAP(强一致性、高可用性、分区容错性)
  • Zookeeper 主节点挂掉会选举新的,期间集群不可用 所以是 强一致性和分区容错性:::::CP
  • Eureka 节点挂掉不会立即删除该节点,平等关系,集群自动切换节点,高可用性和分区容错性 ::::AP
server:
  port: 7001


##  Eureka server和client之间每隔30秒会进行一次心跳通信,告诉server,client还活着。
#禁止注册server自己为client,不管server是否禁止,阈值(threshold)是1。client个数为n,阈值为1+2*n(此为一个server且禁止自注册的情况)
#保护状态实际上是考虑了client和server之间的心跳是因为网络问题,而非服务本身问题,不能简单的删除注册信息。
#在此状态下,server不会删除注册信息,这就有可能导致在调用微服务时,实际上服务并不存在。
#  1、在生产上可以开自注册,部署两个server
#  2、在本机器上测试的时候,可以把比值调低,比如0.49
#  3、或者简单粗暴把自我保护模式关闭


#Eureka 配置 服务注册与发现
eureka:
  server:
    enable-self-preservation: false # 关闭自我保护模式,
  instance:
    hostname: eureka01.server.com   #  注册中心地址
  client:
    register-with-eureka: false   #  剔除自身注册到注册中心
    fetch-registry: false   # 默认是true,,,如果为false表示为注册中心
    service-url:    # 标识监控页面地址::默认是  defaultZone:http://localhost:8761/eureka/
      #defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/  # 单机
      #集群的话需要设计关联 (集群服务)
      defaultZone: http://eureka02.server.com:7002/eureka/,http://eureka03.server.com:7003/eureka/

spring:
  application:
    name: eureka-server01

服务通讯 RestTemplate

Springboot自带的RestTemplate工具

@RestController
public class ServiceToService {
    /**
     * Description:  restTemplate远程调用
     */
    @Autowired
    private RestTemplate restTemplate;


    /**
     * Description:  服务间调度采用基于RESTFUL的方式,,基于SprigBoot提供的RestTemplate模板
     * 访问的生产者的地址:CommonDataEntity.PROD_PREFIX ===》 "http://localhost:8888/";
     */
    @RequestMapping("/getProdService")
    public ResponseEntity getProdService() {
        String URI = "getData";
        ResponseEntity forEntity = restTemplate.getForEntity(CommonDataEntity.PROD_PREFIX + URI, ResultEntity.class);
        return forEntity;
    }


    /**
     * Description: 如果是集群的,并且负载均衡的话,通过RIbbon去负载均衡寻找的服务是动态变量
     * 所以通过服务名来访问。然后请求的服务有Ribbon 负载均衡到集群的某一个注册中心服务。
     * 由RestTemplate模板工具跨服务调用。消费功能
     */
    @RequestMapping("/getProdServiceByRibbon")
    public Object getProdServiceByRibbonInColony() {
        // CommonDataEntity.PROD_PREFIX  || http://localhost:8888/  不可用了,有集群的负载,所以通过服务名来访问
        String ribbonColonyProdService = "http://PRODSERVICE/";
        String URI = "getDataByMysql";
        ResultEntity forObject = restTemplate.getForObject(ribbonColonyProdService + URI, ResultEntity.class);
        return forObject;
    }
}

Ribbon 负载均衡 IRule

/**
 * @description: 自定义负载均衡策略
 **/
@Configuration
public class MyGtonRule {

    /**
     * Description: 默认的负载均衡是 RoundRobinRule(轮询)
     */
    @Bean
    public IRule myDiyRuleLoadBalanced(){
        //修改默认负载均衡策略,采用随机访问执行的负载均衡
        return new RandomRule();
    }
	
    @Bean
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
	
	/**
     * Description: 本身RestTemplate未注册到Spring,手动注册  ---->  @Bean
     * <p>
     * Description: 配置Ribbon负载均衡 ,实现基于RestTemplate的负载均衡即可  ----->  @LoadBalanced
     * <p>
     * 服务间的调度基于RESTFUL方式可以通过RestTemplate 请求来完成
     * <p>
     * Ribbon 负载均衡是基于客户端|消费者来完成的   进程式:实现负载均衡,需要配置Eureka注册中心。
     * <p>
     * 默认的负载均衡策略是  轮询 RoundRoRule
     * <p>
     * 自定义负载均衡策略:
     * IRule接口{
     * 轮询 RoundRoRule、
     * 随机选择 RandomRule、
     * 过滤故障服务后轮询 AvailabilityFilteringRule
     * 轮询失败就重试:RetryRule}
     */

}

Feign 内置负载均衡集成Ribbon ,同时提供服务通讯

 * @description: 利用feign基于接口的远程调用和负载均衡
 **/
@Component // fallbackFactory  服务降级
@FeignClient(value = "PRODSERVICE", fallbackFactory = ServiceHystrixFallBack.class)
public interface FeginByService {


    /**
     * Description: 获取所有表数据
     */
    @GetMapping("/getByFeignInUser")
    List<User> getListsByFeign();

    /**
     * Description:  根据ID 获取指定用户
     * @return:
     */
    @GetMapping("/getByFeignInId/{userId}")
    User getUserById(@PathVariable("userId") int userId);
}

@EnableFeignClients(basePackages = {"com.gton"})

import java.util.List;

@RestController
public class ServiceToService {
    /**
     * Description: 基于feign的远程调用与负载均衡
     */

    @Autowired
    private FeginByService feginByService;

    @RequestMapping("/getALl")
    public List<User> getAllByFeign() {
        return this.feginByService.getListsByFeign();
    }

    @RequestMapping("/getById/{id}")
    public User getById(@PathVariable("id") int id) {
        return feginByService.getUserById(id);
    }
}

Hystrix 服务熔断 、服务降级 、dashboard监控

  • 服务熔断

    @GetMapping("/getByFeignInId/{userId}")
    @HystrixCommand(fallbackMethod = "getUserByIdToHystrix")
    public User getUserById(@PathVariable("userId") int userId) {
        User user = userService.getUserById(userId);
        if (user == null) {
            throw new RuntimeException("id:" + userId + ",不存在");
        }
        return user;
    }

    /**
     * Description: 上面的接口失败后:被选方案
     * @author: GuoTong
     * @date: 2021-06-09 21:58:56
     * @param:
     * @return:
     */
    public User getUserByIdToHystrix(@PathVariable("userId") int userId) {
        //原服务出现问题时,Hystrix被选替换原崩溃服务
        return new User().setId(1001).
                setName("Hystrix被选方案:传入ID无效").
                setAddress("localhost").
                setAge(20).
                setEmail("guotong199114@163.com").
                setQq("1054769749");
    }
  • 服务降级
/**
 * @description: 服务熔断--->降级
 **/
@Component
public class ServiceHystrixFallBack implements FallbackFactory<FeginByService> {
    @Override
    public FeginByService create(Throwable throwable) {

        return new FeginByService() {
            @Override
            public List<User> getListsByFeign() {
                List<User> users = new ArrayList<>();
                users.add(new User().setAddress("服务已降级-不可用"));
                return users;
            }

            @Override
            public User getUserById(int userId) {
                return new User().setAddress("服务已降级-不可用");
            }
        };
    }
}

  • 服务监控
 **/
@SpringBootApplication
@EnableHystrixDashboard  //开启Hystrix监控
public class ConsumerHystrixHashBoard {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerHystrixHashBoard.class, args);
    }
}

服务网关 Zuul

@SpringBootApplication
@EnableZuulProxy //开启网关代理
public class ZuulApplication {

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

application.yml

server:
  port: 9527
spring:
  application:
    name: springcloud-zuul-gateway

#Eureka 配置 消费者不注册,主要指集成负载均分Ribbon
eureka:
  client:
    register-with-eureka: true # 向Eureka中注册自己,
    #集群注册中心  消费者关联所有的注册中心,基于ribbon实现服务负载均衡
    service-url:
      defaultZone: http://eureka01.server.com:7001/eureka/,http://eureka02.server.com:7002/eureka/,http://eureka03.server.com:7003/eureka/
  instance:
    instance-id: zuul9527.com
    prefer-ip-address: true


info:
  app.name: guotong-netflix-springcloud
  username: guotong


#默认就是网关加上应用ID加资源路径即可
zuul:
  routes:
    #xxxx.serviceId ||xxxx.path ==>xxxx是你的路由映射 ==》/xxxx/**
    prod:
      # 应用名称
      serviceId: prod-service    #使用服务名访问
      #prod.id: /prod/**
      path: /prod/**     #使用别名
  ignored-services: "*"    #不能使用原服务名这个路径访问  prod-service  或者 通配符
  prefix: /gton    #设置公共的访问前缀

分布式配置中心 Springcloud-config C/S架构 -git

服务端

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

客户端:

spring:
  application:
    name: springcloud-config-client
  cloud:
    config:
      uri: http://localhost:3344
      name: config-client # 在git上读取的资源名称
      profile: dev  # 访问环境
      label: master # 访问分支
server:
  port: 3355

核心:导入依赖,编写配置,开启注解

posted on 2021-07-04 20:18  白嫖老郭  阅读(283)  评论(0编辑  收藏  举报

导航