Ribbon,OpenFegin

124 阅读2分钟

Ribbon

LB 负载均衡 (Load Balance) 是什么

简单的说就是将用户的请求平均的分配到多个服务器上,从而达到高可用HA。常见的负载均衡软件有Nginx,LV5,硬件F5

Ribbon本地负载均衡和Nginx服务器负载均衡区别

Nginx是服务器的负载均衡,客户端所有请求接口都会交给ngnix,然后由nginx实现请求妆发。即负载均衡是由服务器端实现的。

Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取信息服务列表之后缓存在本地JVM,从而在本地实现RPC远程调用。

几种不同的轮询规则

图片.png

如何替换使用不同的轮询规则

重新建立一个类,但是这个类不能被ComponentScan这个注解扫描到

图片.png

主启动类上添加RibbonClient注解

图片.png

负载均衡算法

rest接口第几次请求数 % 服务器总数量 = 实际调用服务器位置下标 , 每次重启服务后rest从1开始计数。

图片.png

OpenFegin

Fegin能做什么,Ribbon + RestTemplate 利用RestTemplate对http请求的封装处理,形成一套模板化的调用方法。但是在实际开发过程中,对服务依赖调用可能不止溢出,往往一个接口会被多个地方调用,所以通常都会针对每一个微服务自行封装一些客户端类来包装这些依赖服务的调用,所以,Fegin在次基础上做封装,由他来帮助我们定义和实现依赖服务接口定义,在Fegin的实现下,我们只需要创建一个接口并使用注解的方式来配置即可,完成对服务提供方的接口绑定,简化了使用Spring Cloud Ribbon时,自动封装服务调用客户端的开发量。

OpenFegin远程调用

创建新的模块cloud-consumer-fegin-order80

pom

<dependencies>
    <!--OpenFegin-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>
    <!--Eureka 客户端-->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <version>2.2.1.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>com.nyc.cloud</groupId>
        <artifactId>cloud-api-commons</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>


    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-actuator</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>
</dependencies>

yml

server:
  port: 80

eureka:
  client:
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

  application:
    name: consumer-oder-openfeign

service

@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeginService {

    @GetMapping(value = "/payment/get/{id}")
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}

启动类

@SpringBootApplication
@EnableFeignClients
public class OrderFeginMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeginMain80.class);
    }
}

调用接口

图片.png

OpenFegin超时控制和日志

Fegin的调用时间默认是 1秒如果超过这个调用时间就会报错。添加如下配置即可让这个调用时间增长。

ribbon:
  #指的是建立链接所用的事件,适用于网络正常情况下,两端链接所需要的时间
  ReadTimeout: 5000
  #值的是建立后从服务器读取到可用资源所用时间
  Connectimeout: 5000
  logging:
    level:
      #fegin日志以什么级别监控那个端口
      com.atguigu.springcloud.service.PaymentService: debug