zoukankan      html  css  js  c++  java
  • 简单随机算法实现负载均衡

    package util
    
    import (
        "math/rand"
        "time"
    )
    
    type HttpServer struct { //目标server类
        Host string
    }
    
    func NewHttpServer(host string) *HttpServer {
        return &HttpServer{Host: host}
    }
    
    type LoadBalance struct { //负载均衡类
        Servers []*HttpServer
    }
    
    func NewLoadBalance() *LoadBalance {
        return &LoadBalance{Servers: make([]*HttpServer, 0)}
    }
    
    func (this *LoadBalance) AddServer(server *HttpServer) {
        this.Servers = append(this.Servers, server)
    }
    
    func (this *LoadBalance) SelectForRand() *HttpServer {
        rand.Seed(time.Now().UnixNano())
        index := rand.Intn(len(this.Servers))
        return this.Servers[index]
    }
    
    func (this *LoadBalance) SelectByIpHash(ip string) *HttpServer {
        index := int(crc32.ChecksumIEEE([]byte(ip))) % len(this.Servers) //通过取余永远index都不会大于this.servers的长度
        return this.Servers[index]
    }
    




  • 相关阅读:
    净化-湿式除尘器:湿式除尘器
    净化-袋式除尘器:袋式除尘器
    LOCK
    locale
    loadkeys
    LOAD
    ln -在文件之间建立连接
    lmhosts
    listen
    listalias
  • 原文地址:https://www.cnblogs.com/hualou/p/12070702.html
Copyright © 2011-2022 走看看