自定义Ribbon客户端策略

说明

  为了实现Ribbon细粒度的划分,让调用不同的微服务时采用不同的客户端负载均衡策略, 通常情况下我们会自定义配置策略。

  本文以内容中心(content-center)调用户中心微服务(user-center)为例子进行演示

sample

内容中心包结构如下图所示:

construct

版本选择

Spring Boot Spring Cloud Spring Cloud Netflix Ribbon
2.1.5.RELEASE Greenwich.SR3 2.1.3.RELEASE

方式一、通过Java代码配置

RandomConfiguration.java

package ribbonconfiguration;

import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * description: 随机的负载均衡策略
 * jdk: 1.8
 */
@Configuration
public class RandomConfiguration {

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

}

UserCenterConfiguration.java


package com.itnotes.contentcenter.configuration;

import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Configuration;
import ribbonconfiguration.RandomConfiguration;

/**
 * description:
 * jdk: 1.8
 */
@Configuration
@RibbonClient(name = "user-center", configuration = RandomConfiguration.class)
public class UserCenterConfiguration {
}

  这样我们就能实现,从内容中心调用用户中心微服务时走自定义的策略,不过通过这种方式实现时有一个坑需要注意,那就是自定义的策略所在类(RandomConfiguration.java)不能被@SpringBootApplication的@ComponentScan给扫描到,因为他们存在父子上下文的问题,如果被扫描到,那么内容中心所有的RibbonClient都会走该策略,其他策略会失效。

我们可以看一下官网的说明

The CustomConfiguration clas must be a @Configuration class, but take care that it is not in a @ComponentScan for the main application context. Otherwise, it is shared by all the @RibbonClients. If you use @ComponentScan (or @SpringBootApplication), you need to take steps to avoid it being included (for instance, you can put it in a separate, non-overlapping package or specify the packages to scan explicitly in the @ComponentScan).

Ribbon 官网介绍

方式二、属性配置(通过配置文件的方式)

这种方式比较简单,直接在.yml或者.properties文件配置即可

在本例中我们在内容中心配置如下(value是所选择负载均衡策略的全路径)

user-center:
  ribbon:
    NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule

两种方式的对比

配置方式 优点 缺点
代码配置 基于代码,更加灵活 有小坑(父子上下文), 线上修改需重新打包、发布
属性配置 易上手,配置更加直观,线上修改无需打包、发布,优先级更高 极端场景下没有代码配置灵活

最佳实践

  • 尽量使用属性配置,属性方式实现不了再考虑代码配置。因为属性配置没有父子上下文的坑,并且更加直观。

  • 在同一个微服务内的配置方式尽量保持单一性,两种方式不要混用,避免增加问题定位的复杂性

猜你喜欢

转载自www.cnblogs.com/devise/p/11769153.html
今日推荐