码迷,mamicode.com
首页 > 编程语言 > 详细

简单随机算法实现负载均衡

时间:2019-12-19 23:24:40      阅读:128      评论:0      收藏:0      [点我收藏+]

标签:package   sel   app   balance   play   adb   time   code   pre   

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]
}




简单随机算法实现负载均衡

标签:package   sel   app   balance   play   adb   time   code   pre   

原文地址:https://www.cnblogs.com/hualou/p/12070702.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!