springcloud-04-自定义ribbon的配置方式

在dubbo项目中, zookeeper即注册中心帮我们实现了调度和负载均衡的能力, 这种方式被称为服务器端的负载均衡, springcloud中, 使用ribben实现的客户端负载均衡

什么是ribbon?

Ribbon是Netflix发布的云中间层服务开源项目,其主要功能是提供客户端侧负载均衡算法。Ribbon客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,Ribbon是一个客户端负载均衡器,我们可以在配置文件中列出Load Balancer后面所有的机器,Ribbon会自动的帮助你基于某种规则(如简单轮询,随机连接等)去连接这些机器,我们也很容易使用Ribbon实现自定义的负载均衡算法。

eureka使用ribbon的大致架构

Ribbon工作时分为两步:第一步先选择 Eureka Server, 它优先选择在同一个Zone且负载较少的Server;第二步再根据用户指定的策略,在从Server取到的服务注册列表中选择一个地址。其中Ribbon提供了多种策略,例如轮询round robin、随机Random、根据响应时间加权等。

通过代码实现:

将刚才的cosumer-movie改造成ribbon的项目

添加一个注解类, 需要放置在mainClass扫描不到的包下, 或者在mainClass中通过@COmponentScan进行过滤

这儿使用的是注解过滤, 所以首先需要一个注解:

package com.wenbronk.cosumer.ribben.annotation;

/**
 * 自定义注解, 排除不想被扫描到的内容
 * Created by wenbronk on 2017/5/18.
 */
public @interface ExcudeAnnotation {
}

然后是一个ribbon的注解声明类:

package com.wenbronk.cosumer.ribben.config;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import com.wenbronk.cosumer.ribben.annotation.ExcudeAnnotation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 默认规则为轮询, 这个为随机规则
 * 该类必须放置在扫描不到的包下, 或者添加排除, 虽然他必须有注解
 * Created by wenbronk on 2017/5/18.
 */
@Configuration
@ExcudeAnnotation
public class MyRibbonConfig {

    @Bean
    public IRule ribbonRule() {
        return new RandomRule();
    }

}

在mainClass中进行过滤

package com.wenbronk.cosumer.ribben;

import com.wenbronk.cosumer.ribben.annotation.ExcudeAnnotation;
import com.wenbronk.cosumer.ribben.config.MyRibbonConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.client.RestTemplate;

/**
 * 通过RIbbonClient自定义ribbon客户端
 * Created by root on 2017/5/18.
 */
@SpringBootApplication
@EnableEurekaClient
// 使用此规则不可放在 可扫描的路径下, 如果非要放置, 需要加自定义注解
@RibbonClient(name = "microserver-provider-user", configuration = MyRibbonConfig.class)
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {ExcudeAnnotation.class})})
public class MovieRibbenApplication {

    /**
     * 使用LoadBalanced开启客户端负载均衡的功能
     * @return
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

}

验证:

通过配置端口, 将user服务启动4个实例, 并注册为2个服务, 在movie-ribbon的controller中加入如下代码

package com.wenbronk.cosumer.ribben.controller;

import com.wenbronk.cosumer.ribben.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by root on 2017/5/18.
 */
@RestController
public class MovieRibbenController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
    }

    @GetMapping("/test")
    public void test() {
        ServiceInstance instance = this.loadBalancerClient.choose("MICROSERVICE-PROVIDER-USER");
        System.out.println("111: " + instance.getServiceId() + ": " + instance.getHost() + ": " + instance.getPort());
//        System.out.println(instance.toString());

        ServiceInstance instance1 = this.loadBalancerClient.choose("MICROSERVICE-PROVIDER-USER-1");
        System.out.println("222: " + instance1.getServiceId() + ": " + instance1.getHost() + ": " + instance1.getPort());
//        System.out.println(instance1);
//        System.out.println(instance == instance1);
    }
}

通过浏览器重复的发送请求, 在控制台可看到只有provide-user 使用了我们自定义的规则, user-1 仍然使用的ribbon的默认规则轮询

通过配置文件的方式, 自定义ribbonclient:

从版本1.2.0开始,Spring Cloud Netflix现在支持使用属性与Ribbon文档兼容来自定义Ribbon客户端。

配置的优先级: 配置文件 >  java代码 > springcloud default

配置文件配置, 只需要在yml‘中添加如下内容

users:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.WeightedResponseTimeRule
NFLoadBalancerRuleClassName 是规则, 除了此规则 springcloud还有
每个规则可添加的类也有很多 

mainClass.java

package com.wenbronk.cosumer.ribbon.yml;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

/**
 * Created by wenbronk on 2017/5/20.
 */
@SpringBootApplication
@EnableEurekaClient
public class MoveiRibbonYmlApplicatoin {

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

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

MovieRibbonController

package com.wenbronk.cosumer.ribbon.yml.controller;

import com.wenbronk.cosumer.ribbon.yml.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * Created by root on 2017/5/18.
 */
@RestController
public class MovieRibbenController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @RequestMapping("/movie/{id}")
    public User findById(@PathVariable Long id) {
        return restTemplate.getForObject("http://microservice-provider-user/simple/" + id, User.class);
    }

    @GetMapping("/test")
    public void test() {
        ServiceInstance instance = this.loadBalancerClient.choose("MICROSERVICE-PROVIDER-USER");
        System.out.println("111: " + instance.getServiceId() + ": " + instance.getHost() + ": " + instance.getPort());
//        System.out.println(instance.toString());

        ServiceInstance instance1 = this.loadBalancerClient.choose("MICROSERVICE-PROVIDER-USER-1");
        System.out.println("222: " + instance1.getServiceId() + ": " + instance1.getHost() + ": " + instance1.getPort());
//        System.out.println(instance1);
//        System.out.println(instance == instance1);
    }
}

  

时间: 2024-08-06 13:39:01

springcloud-04-自定义ribbon的配置方式的相关文章

springCloud(8):Ribbon实现客户端侧负载均衡-自定义Ribbon配置

一.简介 很多场景下,可能根据需要自定义的Ribbon的配置,例如修改Ribbon的负载均衡规则等.Spring cloud Camden允许使用Java代码或属性自定义Ribbon的配置. 二.使用Java代码自定义Ribbon配置 在Spring cloud中,Ribbon的默认配置如下,格式是:BeanType beanName:ClassName 1.IClientConfig ribbonClientConfig:DefaultClientConfigImpl 2.IRule ribb

0404-Ribbon通过代码自定义配置、使用配置文件自定义Ribbon Client

一.官方文档解读 官方地址:https://cloud.spring.io/spring-cloud-static/Edgware.SR3/single/spring-cloud.html#_customizing_the_ribbon_client 二.自定义Ribbon客户端-配置类 2.1.自定义负载规则 步骤一.增加TestConfiguration配置类 @Configuration public class TestConfiguration { public IRule ribbo

SpringCloud系列五:Ribbon 负载均衡(Ribbon 基本使用、Ribbon 负载均衡、自定义 Ribbon 配置、禁用 Eureka 实现 Ribbon 调用)

1.概念:Ribbon 负载均衡 2.具体内容 现在所有的服务已经通过了 Eureka 进行了注册,那么使用 Eureka 注册的目的是希望所有的服务都统一归属到 Eureka 之中进 行处理,但是现在的问题,所有的微服务汇集到了 Eureka 之中,而客户端的调用也应该通过 Eureka 完成.而这种调用就可以利用 Ribbon 技术来实现. Ribbon 是一个服务调用的组件,并且是一个客户端实现负载均衡处理的组件.服务器端实现负载均衡可以使用 Nginx. HAProxy.LVS 等. 2

SpringCloud | FeignClient和Ribbon重试机制区别与联系

在spring cloud体系项目中,引入的重试机制保证了高可用的同时,也会带来一些其它的问题,如幂等操作或一些没必要的重试. 今天就来分别分析一下 FeignClient 和 Ribbon 重试机制的实现原理和区别,主要分为三点: 1)FeignClient重试机制分析 2)Ribbon重试机制分析 3)FeignClient和Ribbon重试机制的区别于联系 1)FeignClient 重试机制分析: FeignClient 重试机制的实现原理相对简单.首先看一下feignClient处理请

笔记:Spring Cloud Ribbon 客户端配置详解

自动化配置 由于 Ribbon 中定义的每一个接口都有多种不同的策略实现,同时这些接口之间又有一定的依赖关系,Spring Cloud Ribbon 中的自动化配置能够很方便的自动化构建接口的具体实现,接口如下: IClientConfig:Ribbon 的客户端配置,默认采用 com.netflix.client.config.DefaultClientConfigImpl 实现. IRule:Ribbon 的负载均衡策略,默认采用 com.netflix.loadbalancer.ZoneA

SpringCloud学习之Ribbon

一.负载均衡与Ribbon 负载均衡,在集群中是很常见的一个“名词”,顾名思义是根据一定的算法将请求分摊至对应的服务节点上,常见的算法有如下几种: 轮询法:所有请求被依次分发到每台应用服务器上,每台服务器需要处理的请求数目都相同,适合所有服务器硬件都相同的场景 随机法:请求被随机分配到各个应用服务器,在许多场合下,这种方案都很简单实用. 源地址哈希(Hash)法:将请求来源的IP地址进行Hash计算,得到对应的服务器,这样来自同一个IP的请求总在同一个服务器上处理 加权法:根据应用服务器配置的情

Ubuntu 14.04下NFS安装配置

Ubuntu 14.04下NFS安装配置 参考:http://www.linuxidc.com/Linux/2013-08/89154.htm 1.执行命令:sudo apt-get install nfs-kernel-server ; 2.执行命令:mkdir /home/jacobxu/nfs-jacoxu 建立一个nfs服务的专有的文件夹; 3.建立好文件夹后,接着执行命令:sudo vi /etc/exports 配置nfs; 4.在文章的最后一行添加:/home/jacobxu/nf

Ubuntu 14.04 上安装和配置 FTP 服务器 ProFTPD

proftpd的配置方式类似apache,比vsftpd更易用,xampp就集成了proftpd. apt-cache search proftpd 搜索相关包 sudo apt-get install proftpd-basic 安装 安装时默认作为一个standalone server运行proftpd,如果每天的ftp请求量少,可以安装为inetd服务,节省服务器资源. 这里我使用默认值,安装为standalone server. sudo netstat -antp|grep proft

Desktop Ubuntu 14.04LTS/16.04科学计算环境配置

Desktop Ubuntu 14.04LTS/16.04科学计算环境配置 计算机硬件配置 cpu i5 6代 内存容量 8G gpu GTX960 显存容量 2G(建议显存在4G以上,否则一些稍具规模的神经网络无法训练,会提示显存容量不足) 配置顺序 安装包 重要依赖 安装ubuntu            14.04   安装显卡驱动         nvidia-367   安装cuda tool kit        8.0   安装cuDNN             v5 安装版本取决