1. 程式人生 > >springcloud負載均衡采用一致性哈希算法

springcloud負載均衡采用一致性哈希算法

obj ans nbsp 進行 ner 默認 private override 方法

  spring cloud網關集成了zuul和熔斷器,因此網關天生具有負載均衡和熔斷的功能。因此spring cloud的負載均衡算法,就是ribbon的負載均衡算法。在ribbon中,負載均衡默認了輪詢的方法。如果想采用一致性哈希算法,實現負載均衡,那應該怎麽辦呢?

  這裏我才用guava的一致性哈希算法,就不自己寫一致性哈希算法了。

  首先pom.xml:

<!--guava緩存cache-->
      <dependency>
          <groupId>com.google.guava</groupId>
          <artifactId>guava</artifactId>
          <version>23.0</version>
      </dependency>

  然後自己寫一個類,集成AbstractLoadBalancerRule:


@Component
public class ConsistentHash extends AbstractLoadBalancerRule {

    private Logger log = LoggerFactory.getLogger(ConsistentHash.class);

    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; } //獲取請求URI RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String URI = request.getServletPath()+"?"+request.getQueryString(); int hashcode = URI.hashCode(); int model = Hashing.consistentHash(hashcode, serverCount); //一致性哈希,直接返回第幾個數 server = allServers.get(model); 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; } @Override public Server choose(Object key) { return choose(getLoadBalancer(), key); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) { // TODO Auto-generated method stub } }

  就完成了。

  如果只是想針對某個應用實現一致性哈希負載均衡,那麽可以以下幾步:

  1.去掉ConsistentHash上面的註解

  2.新建一個類MyRibbonConfiguration:

public class MyRibbonConfiguration {
    @Bean
    public IRule ribbonRule() {
        return new ConsistentHash();//實例化與配置文件對應的策略類
    }
}

  3

@Configuration
@RibbonClient(name = "hello-service", configuration = MyRibbonConfiguration.class)
public class RibbonConfiguration {

}

  這樣就只是針對hello-service進行一致性哈希負載均衡算法,其他 的還是采用輪詢。

springcloud負載均衡采用一致性哈希算法