SpringCloud之服务调用(总体第三篇笔记)

前面相关文章已经学习到了我们的SpringCloud的服务注册相关内容,接下来学习内容如下。

一、Ribbon负载均衡服务调用

启动我们的项目
在这里插入图片描述
在这里插入图片描述

1、SpringCloud Ribbon是什么

在这里插入图片描述

  • 进入了维护模式
    在这里插入图片描述
    未来的替换方案是SpringCloud Loadbalance

  • 能干什么
    在这里插入图片描述
    Nginx
    在这里插入图片描述
    Ribbon
    在这里插入图片描述
    80通过轮巡负载访问8001/8002

2、Ribbon负载均衡和REST调用

(1)介绍

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 分析原因:我们之前并没有引入Ribbon,就可以实现负载均衡了呢?
    在这里插入图片描述
    引入这个,其实它就做了内部的整合
    在这里插入图片描述
    在这里插入图片描述

(2)再来看看RestTemplate

  • RestTemplate主要有四个方法可以用
    • getForObject方法:返回的对象为响应体中的数据转化为对象,基本上可以理解为JSON。
    • getForEntity方法:返回对象为ResponseEntity对象,包含了响应体中的一些重要信息,比如响应头,响应状态码,响应体等。
    • postForObject方法和postForEntity方法
      在这里插入图片描述

(3)案例演示

  • 测试getForEntity方法
    在这里插入图片描述
    启动如下进行辨别
    在这里插入图片描述
    在这里插入图片描述
    可以像如下或取更多信息,但是不建议用
    在这里插入图片描述

3、Ribbon自带的负载规则

可以使用IRule接口,根据特定的算法从服务列表中选择一个访问的服务。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(1)如何替换默认的负载均衡

  • 它默认的第一种轮巡
    在这里插入图片描述
    在这里插入图片描述
    不要放在我们的cn.mldn.springcloud包下
  • 修改我们的order
    在这里插入图片描述
  • 新建配置类【定义为随机】
    在这里插入图片描述
  • 配置主启动
    在这里插入图片描述
  • 启动测试
    之前是8001和8002轮着来,但是现在就不是了。

4、Ribbon默认轮巡算法

(1)原理

  • 首先恢复之前的算法问轮巡
    在这里插入图片描述
    这个比较好理解的吧,毕竟这里就两台机器。

(2)源代码

/*
 *
 * Copyright 2013 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.netflix.loadbalancer;

import com.netflix.client.config.IClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * The most well known and basic load balancing strategy, i.e. Round Robin Rule.
 *
 * @author stonse
 * @author Nikos Michalakis <nikos@netflix.com>
 *
 */
public class RoundRobinRule extends AbstractLoadBalancerRule {

    private AtomicInteger nextServerCyclicCounter;
    private static final boolean AVAILABLE_ONLY_SERVERS = true;
    private static final boolean ALL_SERVERS = false;

    private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);

    public RoundRobinRule() {
        nextServerCyclicCounter = new AtomicInteger(0);
    }

    public RoundRobinRule(ILoadBalancer lb) {
        this();
        setLoadBalancer(lb);
    }

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            log.warn("no load balancer");
            return null;
        }

        Server server = null;
        int count = 0;
        while (server == null && count++ < 10) {
            List<Server> reachableServers = lb.getReachableServers();
            List<Server> allServers = lb.getAllServers();
            int upCount = reachableServers.size();
            int serverCount = allServers.size();

            if ((upCount == 0) || (serverCount == 0)) {
                log.warn("No up servers available from load balancer: " + lb);
                return null;
            }

            int nextServerIndex = incrementAndGetModulo(serverCount);
            server = allServers.get(nextServerIndex);

            if (server == null) {
                /* Transient. */
                Thread.yield();
                continue;
            }

            if (server.isAlive() && (server.isReadyToServe())) {
                return (server);
            }

            // Next.
            server = null;
        }

        if (count >= 10) {
            log.warn("No available alive servers after 10 tries from load balancer: "
                    + lb);
        }
        return server;
    }

    /**
     * Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
     *
     * @param modulo The modulo to bound the value of the counter.
     * @return The next value.
     */
    private int incrementAndGetModulo(int modulo) {
        for (;;) {
            int current = nextServerCyclicCounter.get();
            int next = (current + 1) % modulo;
            if (nextServerCyclicCounter.compareAndSet(current, next))
                return next;
        }
    }

    @Override
    public Server choose(Object key) {
        return choose(getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}

(3)手写轮巡算法

  • 首先改变如下
    在这里插入图片描述
    在这里插入图片描述

在这里插入图片描述

  • 建类和方法
    在这里插入图片描述
    在这里插入图片描述

二、服务器调用

1、Feign和OpenFeign

  • 首先Feign已经不用学了,已经停了
  • Feign是一个声明式WebService喀户端。 使用Feign能让编写Web Service客户端更加简单。它的使用方法是定义一个服务接口然后在 上面添加注解。Feign支持可拔插式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters. Feign可以与Eureka和Ribbon组合使用以支持负载均衡
  • penFeign 是 Spring Cloud 家族的一个成员, 它最核心的作用是为 HTTP 形式的 Rest API 提供了非常简洁高效的 RPC 调用方式
    在这里插入图片描述

2、Feign能干什么

在这里插入图片描述
就相当于接口提供方,给它创建一个同样的。

3、如何使用OpenFeign

(1)搭建环境

  • 恢复昨天的环境
    在这里插入图片描述
  • 之前实现的负载均衡
    在这里插入图片描述
  • 现在就用feign【微服务接口调用+feign】
    在这里插入图片描述

(2)代码实现

  • 建项目
    在这里插入图片描述
  • 导入依赖
<dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 引入自己定义的api通用包,可以使用Payment支付Entity -->
        <dependency>
            <groupId>cn.mldn</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--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>
        <!--一般基础通用配置-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 配yml
server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  • 主启动
    在这里插入图片描述
  • 业务逻辑接口+调用@FeignClient配置调用provider服务
    在这里插入图片描述
    它去调用8001暴露出来的服务。

(3)Feign自带了Ribbon

服务器接口,+ FeignClient进行处理,它内部集成了我们的Ribbon。

4、OpenFeign超时重传

(1)首先模拟一个效果说明

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

(2)原因

OpenFeign默认等待一秒钟,超时后报错。
在这里插入图片描述

(3)解决办法

  • 在yml文件里面开启配置
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
  #指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间,单位为毫秒
  ReadTimeout: 5000
  #指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

5、OpenFeign日志增强

在这里插入图片描述

在这里插入图片描述

  • 这样配置
logging:
  level:
    # feign日志以什么级别监控哪个接口
    cn.mldn.springcloud.service.PaymentFeignService: debug

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值