• 轮询算法


    package util
    
    import (
        "fmt"
        "hash/crc32"
        "math/rand"
        "time"
    )
    
    type HttpServer struct { //目标server类
        Host   string
        Weight int
    }
    
    func NewHttpServer(host string, weight int) *HttpServer {
        return &HttpServer{Host: host, Weight: weight}
    }
    
    type LoadBalance struct { //负载均衡类
        Servers  []*HttpServer
        CurIndex int //指向当前访问的服务器
    }
    
    func NewLoadBalance() *LoadBalance {
        return &LoadBalance{Servers: make([]*HttpServer, 0)}
    }
    
    func (this *LoadBalance) AddServer(server *HttpServer) {
        this.Servers = append(this.Servers, server)
    }
    
    func (this *LoadBalance) RoundRobin() *HttpServer {
        server := this.Servers[this.CurIndex]
        //this.CurIndex++
        //if this.CurIndex >= len(this.Servers) {
        //    this.CurIndex = 0
        //}
        this.CurIndex = (this.CurIndex + 1) % len(this.Servers) //因为一个数的余数永远在0-它本身之间,所以用这种方式得到的轮询更好
        return server
    }
    
    var LB *LoadBalance
    var ServerIndices []int
    
    func init() {
        LB = NewLoadBalance()
        LB.AddServer(NewHttpServer("http://localhost:8001/web1", 5))  //web1
        LB.AddServer(NewHttpServer("http://localhost:8002/web2", 15)) //web2
        for index, server := range LB.Servers {
            if server.Weight > 0 {
                for i := 0; i < server.Weight; i++ {
                    ServerIndices = append(ServerIndices, index)
                }
            }
        }
    }




  • 相关阅读:
    Android开发日记(三)
    Android开发日记(二)
    Bundle savedInstanceState的作用
    Android Bundle类
    Consumer
    饭卡
    《CLR via C#》读书笔记 之 泛型
    WCF寄宿到Windows Service
    WCF中配置文件解析
    WCF Service Configuration Editor的使用
  • 原文地址:https://www.cnblogs.com/hualou/p/12070723.html
Copyright © 2020-2023  润新知