【后端开发】尚硅谷 SpringCloud 学习笔记

这篇具有很好参考价值的文章主要介绍了【后端开发】尚硅谷 SpringCloud 学习笔记。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


一、cloud组件

【后端开发】尚硅谷 SpringCloud 学习笔记

二、环境搭建

2.1 创建父工程

【后端开发】尚硅谷 SpringCloud 学习笔记

2.2 支付模块构建

【后端开发】尚硅谷 SpringCloud 学习笔记

2.3 消费者模块构建

2.3.1 引入RestTemplate

@Configuration
public class ApplicationContextConfig {
    // 配置bean 不然后面没法依赖注入,就像以前ssm整合时配置依赖注入一样,
    // 需要在配置文件配置之后,代码中才可以依赖注入
    // 当前文件就是spring的配置文件
    @Bean
//    @LoadBalanced //让这个RestTemplate在请求时拥有客户端负载均衡的能力  //将此注解注释掉,使用自己的轮询算法不使用默认的
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

2.3.2 远程调用支付模块

@RestController
public class OrderController {

    public static final String PAYMENT_URL = "http://localhost:8001";

    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/testRPC/{id}")
    public CommonResult<Payment> getPayment(@PathVariable("id") String id) {
        return restTemplate.getForObject(PAYMENT_URL + "/test/" + id, CommonResult.class);
    }
    
}

三、Eureka

3.1 基础知识

前面我们没有服务注册中心,也可以服务间调用,为什么还要服务注册?

当服务很多时,单靠代码手动管理是很麻烦的,需要一个公共组件,统一管理多服务,包括服务是否正常运行,等

Eureka用于**服务注册,目前官网已经停止更新**

3.2 单机版Eureka安装

【后端开发】尚硅谷 SpringCloud 学习笔记

创建项目cloud-eureka-server-7001

引入依赖

<dependencies>
    <!-- 服务注册中心的服务端 eureka-server -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-server</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-actuator</artifactId>
    </dependency>
    
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
    </dependency>

</dependencies>

yml配置文件

server:
  port: 7001

# 单机版
eureka:
  instance:
    hostname: localhost  #eureka服务端的实例名字
  client:
    register-with-eureka: false    #表示不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://${eureka.instance.hostname}:${server.port}

启动类

/**
 * @author WSKH
 * @date 2020/12/19 14:12
 * @description 注册中心
 */
@SpringBootApplication
@EnableEurekaServer // 启动Eureka服务
public class CloudEurekaServer7001Application {
    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaServer7001Application.class, args);
        System.out.println("启动成功!");
    }
}

3.3 服务注册

引入依赖

<!-- 服务注册中心的客户端端 eureka-client -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

yaml配置

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service
    
eureka:
  client:
    register-with-eureka: true #是否向注册中心注册自己
    fetchRegistry: true #是否从注册中心抓取已有的注册信息 默认true,集群必须设置为true
    service-url:
      #      设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
            defaultZone: http://localhost:7001 #单机版
  instance:
    instance-id: payment8001
    prefer-ip-address: true  #访问路径可以显示IP地址
#    Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
#    lease-renewal-interval-in-seconds: 1
#    Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
#    lease-expiration-duration-in-seconds: 2

启动类

@SpringBootApplication
@EnableEurekaClient // 指定成为Eureka客户端
@EnableDiscoveryClient // 开启服务发现
@Slf4j
public class CloudProviderPayment8001Application {
    public static void main(String[] args) {
        SpringApplication.run(CloudProviderPayment8001Application.class, args);
        log.info("cloud-provider-payment-8001 启动成功!");
    }
}

3.4 Eureka集群

单机版注册中心会出现单点故障,故一般都采用集群

【后端开发】尚硅谷 SpringCloud 学习笔记

两台或以上的Rureka互相注册,相互守望,对外暴露端口

3.4.1 Eureka端配置

【后端开发】尚硅谷 SpringCloud 学习笔记

7001的yaml配置

server:
  port: 7001
  
#集群版
eureka:
  instance:
    hostname: eureka7001    #eureka服务端的实例名字(实际好像不起作用,DS Replicas是直接截取URL中冒号前面的部分,当作队友名,如http://localhost:7001,那就截取localhost当作队友名)
  client:
    register-with-eureka: false    #表示不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
#      defaultZone: http://eureka7001.com:7001
      defaultZone: http://localhost:7002  #这个是集群版开启 互相注册
#  server:
##    关闭自我保护机制,保证不可用服务被及时踢除
#    enable-self-preservation: false
#    eviction-interval-timer-in-ms: 2000

7002的yaml配置

server:
  port: 7002

#集群版
eureka:
  instance:
    hostname: eureka7002    #eureka服务端的实例名字(实际好像不起作用,DS Replicas是直接截取URL中冒号前面的部分,当作队友名,如http://localhost:7001,那就截取localhost当作队友名)
  client:
    register-with-eureka: false    #表识不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://localhost:7001

3.4.2 微服务端配置

【后端开发】尚硅谷 SpringCloud 学习笔记

server:
  port: 80

spring:
  application:
    name: cloud-order-service

eureka:
  client:
    register-with-eureka: true #是否向注册中心注册自己
    fetchRegistry: true #是否从注册中心抓取已有的注册信息 默认true,集群必须设置为true
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://localhost:7001,http://localhost:7002  #集群版

【后端开发】尚硅谷 SpringCloud 学习笔记

server:
  port: 8001

spring:
  application:
    name: cloud-payment-service

eureka:
  client:
    register-with-eureka: true #是否向注册中心注册自己
    fetchRegistry: true #是否从注册中心抓取已有的注册信息 默认true,集群必须设置为true
    service-url:
      #      设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
      defaultZone: http://localhost:7001,http://localhost:7002  #集群版
  instance:
    instance-id: payment8001
    prefer-ip-address: true  #访问路径可以显示IP地址
#    Eureka客户端向服务端发送心跳的时间间隔,单位为秒(默认是30秒)
#    lease-renewal-interval-in-seconds: 1
#    Eureka服务端在收到最后一次心跳后等待时间上限,单位为秒(默认是90秒),超时将剔除服务
#    lease-expiration-duration-in-seconds: 2

【后端开发】尚硅谷 SpringCloud 学习笔记

3.4.3 restTemplate负载均衡

加入@LoadBalanced注解即可开启负载均衡

@Configuration
public class ApplicationContextConfig {

    // 配置bean 不然后面没法依赖注入,就像以前ssm整合时配置依赖注入一样,
    // 需要在配置文件配置之后,代码中才可以依赖注入
    // 当前文件就是spring的配置文件
    @Bean
    @LoadBalanced //让这个RestTemplate在请求时拥有客户端负载均衡的能力  //将此注解注释掉,使用自己的轮询算法不使用默认的
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

测试

@RestController
public class OrderController {

    // http://服务名大写
    public static final String PAYMENT_URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("/testLoadBalancedRpc/{id}")
    public CommonResult<Payment> testLoadBalancedRpc(@PathVariable("id") String id) {
        return restTemplate.getForObject(PAYMENT_URL + "/test/"+id, CommonResult.class);
    }

}

【后端开发】尚硅谷 SpringCloud 学习笔记

最后发送请求 http://127.0.0.1:80/testLoadBalancedRpc/id=123 进行测试

发现会自动均衡地访问8001和8002

3.4.4 主机名修改和ip地址显示

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

3.5 服务发现Discovery

开启服务发现

【后端开发】尚硅谷 SpringCloud 学习笔记

使用DiscoveryClient完成服务发现

// 注入DiscoveryClient对象
@Resource
DiscoveryClient discoveryClient;

@GetMapping("/testDiscoveryClient")
public void testDiscoveryClient(){
    // 从注册中心获取所有服务的名称
    List<String> services = discoveryClient.getServices();
    services.forEach(System.out::println);
    // 根据服务名称找到其下的所有实例
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    // 遍历输出实例信息
    instances.forEach(instance -> {
        System.out.println(instance.getServiceId() + "\t" + instance.getHost() + "\t" + instance.getPort() + "\t" + instance.getUri());
    });
}

测试 http://127.0.0.1:8001/testDiscoveryClient

【后端开发】尚硅谷 SpringCloud 学习笔记

3.6 Rureka自我保护机制

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

3.7 禁止Eureka自我保护

【后端开发】尚硅谷 SpringCloud 学习笔记

#集群版
eureka:
  instance:
    hostname: eureka7001    #eureka服务端的实例名字
  client:
    register-with-eureka: false    #表示不向注册中心注册自己
    fetch-registry: false   #表示自己就是注册中心,职责是维护服务实例,并不需要去检索服务
    service-url:
      #设置与eureka server交互的地址查询服务和注册服务都需要依赖这个地址
#      defaultZone: http://eureka7001.com:7001/eureka/
      defaultZone: http://localhost:7002  #这个是集群版开启 互相注册
#  server:
##    关闭自我保护机制,保证不可用服务被及时踢除
#    enable-self-preservation: false
#    eviction-interval-timer-in-ms: 2000

【后端开发】尚硅谷 SpringCloud 学习笔记

四、Zookeeper

五、Consul

5.1 简介

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

5.2 安装

中文官网: https://www.spring.cloud.cc/spring-cloud-consul.html

英文官网:https://www.consul.io

需要下载一个安装包

【后端开发】尚硅谷 SpringCloud 学习笔记

查看版本

【后端开发】尚硅谷 SpringCloud 学习笔记

启动是一个命令行界面,需要输入consul agent -dev启动

http://localhost:8500

【后端开发】尚硅谷 SpringCloud 学习笔记

5.3 搭建项目

引入依赖

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

yaml配置

server:
  port: 8006

spring:
  application:
    name: consul-provider-payment
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

启动类

@SpringBootApplication
@EnableDiscoveryClient //该注解用于向使用consul或者zookeeper作为注册中心时注册服务
public class CloudProviderconsulPayment8006Application {

    public static void main(String[] args) {
        SpringApplication.run(CloudProviderconsulPayment8006Application.class, args);
        System.out.println("启动成功");
    }

}

启动App,查看服务注册情况

六、三个注册中心的异同点

【后端开发】尚硅谷 SpringCloud 学习笔记

七、Ribbon

7.1 入门介绍

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

7.2 使用Ribbon

默认我们使用eureka的新版本时,它默认集成了ribbon:

【后端开发】尚硅谷 SpringCloud 学习笔记

这个starter中集成了reibbon了

我们也可以手动引入ribbon

7.3 RestTemplate类

【后端开发】尚硅谷 SpringCloud 学习笔记

RestTemplate:
        xxxForObject()方法,返回的是响应体中的数据
        xxxForEntity()方法.返回的是entity对象,这个对象不仅仅包含响应体数据,还包含响应体信息(状态码等)

7.4 Ribbon常用负载均衡算法

IRule接口,Riboon使用该接口,根据特定算法从所有服务中,选择一个服务,

Rule接口有7个实现类,每个实现类代表一个负载均衡算法

【后端开发】尚硅谷 SpringCloud 学习笔记

7.5 Ribbon负载均衡规则替换

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jqERrsdi-1686926847827)(…/…/AppData/Roaming/Typora/typora-user-images/image-20220423202944560.png)]

【后端开发】尚硅谷 SpringCloud 学习笔记

配置类

@Configuration
public class MySelfRule {
    @Bean
    public IRule myRule() {
        // 此处将ribbon默认使用的轮询策略改为随机策略
        return new RandomRule();
    }
}

启动类

@SpringBootApplication
@EnableEurekaClient
@EnableDiscoveryClient
// 启动CLOUD-PAYMENT-SERVICE服务时去加载自定义的ribbon配置
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE", configuration = MySelfRule.class)
@Slf4j
public class CloudConsumerOrder80Application {

    public static void main(String[] args) {
        SpringApplication.run(CloudConsumerOrder80Application.class, args);
        log.info("cloud-consumer-order-80 启动成功!");
    }

}

7.6 轮询算法原理

【后端开发】尚硅谷 SpringCloud 学习笔记

7.7 源码分析

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

7.8 手写轮询算法

【后端开发】尚硅谷 SpringCloud 学习笔记

public interface MyLoadBalancer {

    /**
     * 收集服务器总共有多少台能够提供服务的机器,并放到list里面
     *
     * @param serviceInstances
     * @return ServiceInstance
     * @author WSKH
     * @date 2020/12/23 9:24
     */
    ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
@Component
public class MyLB implements MyLoadBalancer {
    // 原子类
    private final AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * @author WSKH
     * @date 2020/12/23 10:07
     * @description 判断时第几次访问
     */
    public final int getAndIncrement() {
        int current;
        String a = "current";
        int next = 0;
        do {
            current = atomicInteger.get();
            // 防止越界
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!atomicInteger.compareAndSet(current, next));
        System.out.println("*****第几次访问,次数next: " + next);
        return next;
    }

    /**
     * 负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标, 每次服务重启动后rest接口计数从1开始。1
     *
     * @param serviceInstances
     * @return ServiceInstance
     * @author WSKH
     * @date 2020/12/23 9:51
     */
    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }

}
// 注入自定义的负载均衡规则
@Resource
private MyLoadBalancer myLoadBalancer;

@Resource
private DiscoveryClient discoveryClient;
/**
 * @author WSKH
 * @date 2020/12/23 10:27
 * @description 测试自定义的负载均衡规则
 */
@GetMapping(value = "/payment/lb")
public String getPaymentLB() {
    List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");

    if (instances == null || instances.isEmpty()) {
        return null;
    }

    // 调用自定义的负载均衡策略
    ServiceInstance serviceInstance = myLoadBalancer.instances(instances);
    URI uri = serviceInstance.getUri();
    return restTemplate.getForObject(uri + "/payment/lb", String.class);

}

八、OpenFeign

8.1 什么是OpenFeign

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

【后端开发】尚硅谷 SpringCloud 学习笔记

8.2 OpenFeign服务调用

未完待续...文章来源地址https://www.toymoban.com/news/detail-497807.html

到了这里,关于【后端开发】尚硅谷 SpringCloud 学习笔记的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Flask框架小程序后端分离开发学习笔记《1》网络知识

    Flask是使用python的后端,由于小程序需要后端开发,遂学习一下后端开发。 协议:http,https (https是加密的http) 主机:g.cn zhihu.com之类的网址 端口:HTTP协议默认是80,因此一般不用填写 路径下面的「/question/31838184」是路径 http://www.zhihu.com/question/31838184 http://www.zhihu.com:80/ 电脑通

    2024年01月17日
    浏览(38)
  • RabbitMQ学习笔记(尚硅谷)

    2.1 流量消峰 2.2 应用解耦 2.3 异步处理 大量数据:Kafaka;高并发:RocketMQ; 中小型数据量少:RabbitMQ 5.1 概念 快递站 5.2 四大概念 生产者,消费者,交换机,队列 交换机可以对应多个队列 5.3 六大模式 简单模式 工作模式 发布/订阅模式 路由模式 主题模式 发布确定模式 5.4 Rab

    2024年02月11日
    浏览(32)
  • 尚硅谷JavaScript高级学习笔记

    JavaScript中函数是对象。我们后续描述构造函数的内存模型时,会将构造函数称为 构造函数对象。 typeof 运算符来查看值的类型,它返回的是类型的字符串值 == 会做数据转换 输出: 每个函数都有一个prototype属性,它默认指向一个0bject空对象(即称为:原型对象) 给原型对象添加

    2024年03月11日
    浏览(39)
  • 尚硅谷ES学习笔记一

    01-开篇 结构化数据:二维表数据 非结构化数据:不能用二维表结构表示的数据:视频、图片,放到nosql中 半结构化数据:将结构和内容混在一起,没有明显的区分。json、xml 02-技术选型 Elasticsearch 是什么 The Elastic Stack, 包括 Elasticsearch、 Kibana、 Beats 和 Logstash(也称为 ELK Sta

    2024年02月04日
    浏览(41)
  • Elasticsearch7学习笔记(尚硅谷)

    Elasticsearch是一个 实时的分布式搜索和分析引擎 。它可以帮助你用前所未有的速度去处理大规模数据。它可以用于 全文搜索,结构化搜索以及分析 ,当然你也可以将这三者进行组合。 Elasticsearch是一个建 立在全文搜索引擎 Apache Lucene™ 基础 上的搜索引擎,可以说Lucene是当今

    2024年01月23日
    浏览(48)
  • [尚硅谷22版shiro]学习笔记

    Apache Shiro 是一个功能强大且易于使用的 Java 安全(权限)框架。Shiro 可以完成:认证、授权、加密、会话管理、与 Web 集成、缓存 等。借助 Shiro 您可以快速轻松地保护任何应用程序——从最小的移动应用程序到最大的 Web 和企业应用程序。 自 2003 年以来,框架格局发生了相当大

    2023年04月08日
    浏览(26)
  • SpringMVC《学习笔记(21版尚硅谷)》

    1、什么是MVC MVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分 M:Model,模型层,指工程中的JavaBean,作用是处理数据 JavaBean分为两类: 一类称为实体类Bean:专门存储业务数据的,如 Student、User 等 一类称为业务处理 Bean:指 Service 或 Dao 对象,专门用于处理业

    2024年02月08日
    浏览(67)
  • 尚硅谷webpack课程学习笔记

    为什么需要使用打包工具? 开发时使用的框架、es6 语法 、less 等浏览器无法识别。 需要经过编译成浏览器能识别的css、js才可以运行。 打包工具可以帮我们编译,还可以做代码压缩、兼容处理、性能优化。 常见的打包工具有什么? vite、webpack、glup、grunt webapck最基本的使用

    2024年02月07日
    浏览(38)
  • 【系统开发】尚硅谷 - 谷粒商城项目笔记(七):消息队列

    Docker中安装 下载镜像: docker pull rabbitmq:management 创建实例并启动: 4369 – erlang发现口 5672 --client端通信口 15672 – 管理界面ui端口 25672 – server间内部通信口 在web浏览器中输入地址:http://服务器ip:15672/ 输入默认账号: guest : guest overview :概览 connections :无论生产者还是消费者

    2024年02月12日
    浏览(38)
  • Flask框架小程序后端分离开发学习笔记《2》构建基础的HTTP服务器

    Flask是使用python的后端,由于小程序需要后端开发,遂学习一下后端开发。本节提供一个构建简单的本地服务器的代码,仔细看注释,学习每一步的流程,理解服务器接收请求,回复响应的基本原理。 代码效果,运行之后,在浏览器输入:localhost:2000 总结 1.导入socket库:这个库

    2024年01月18日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包