Golang implementation of a load balancing algorithm (random, polling)

Source: Internet
Author: User
Tags crc32 sprintf

Code logging

Program Structure Directory

--------Package

Interface {    dobalance ([]*instance, ... string) (*Instance, error)}
Balance.go
Package Balanceimport ("StrConv") Type Instancestruct{hoststringPortint}func newinstance (hoststring, Portint) *Instance {return&instance{host:host, Port:port,}}//methods for defining instance structures GetHost ()Func (P *instance) gethost ()string {    returnP.host}//definition Method Getport ()Func (P *instance) Getport ()int {    returnP.port}func (P*instance) String ()string {    returnP.host +":"+StrConv. Itoa (P.port)}
Instance.go
Package Balanceimport"FMT"type Balancemgrstruct{allbalancer map[string]balancer}varMGR =balancemgr{allbalancer:make (map[string]balancer),}func (P*balancemgr) Registerbalancer (namestring, b Balancer) {P.allbalancer[name]=b}func registerbalancer (namestring, b Balancer) {Mgr.registerbalancer (name, b)}func dobalance (namestring, Insts []*instance] (Inst *Instance, err Error) {balancer, OK:=Mgr.allbalancer[name]if!OK {Err= Fmt. Errorf ("Not found%s balancer", name)return} fmt. Printf ("Use %s balancer\n", name) Inst, err=balancer. Dobalance (insts)return}
Mgr.go
Package Balanceimport ("Errors"    "Math/rand") Func init () {Registerbalancer ("Random", &randombalance{})} Type Randombalancestruct{}func (P*randombalance) dobalance (insts []*instance, Key ...string) (Inst *Instance, err Error) {    ifLen (insts) = =0{Err= errors. New ("No Instance")        return} Lens:=Len (insts) Index:=Rand. INTN (lens) Inst=Insts[index]return}
Random.go
Package Balanceimport ("Errors") Func init () {Registerbalancer ("Roundrobin", &roundrobinbalance{})} Type Roundrobinbalancestruct{Curindexint}func (P*roundrobinbalance) dobalance (insts []*instance, Key ...string) (Inst *Instance, err Error) {    ifLen (insts) = =0{Err= errors. New ("No Instance")        return} Lens:=Len (insts)ifP.curindex >=Lens {P.curindex=0} Inst=Insts[p.curindex] P.curindex= (P.curindex +1) %Lensreturn}
Roundrobin.go

------Entrance

Package Mainimport ("FMT"    "go_dev/day7/example/example1/balance"    "Math/rand"    "OS"    " Time") Func main () {varinsts []*balance. Instance forI: =0; I < -; i++{host:= Fmt. Sprintf ("192.168.%d.%d", Rand. INTN (255), Rand. INTN (255) ) One:= balance. Newinstance (Host,8080) insts=Append (insts, one)}varBalancename ="Random"    ifLen (OS. Args) >1{balancename= OS. args[1]    }     for{Inst, err:=balance. Dobalance (Balancename, insts)ifErr! =Nil {fmt. Println ("Do balance err:", err) fmt. fprintf (OS. Stdout,"Do balance err\n")            Continue} fmt. PRINTLN (Inst) time. Sleep (time. Second)}}
Main.go
Package Mainimport ("FMT"    "go_dev/day7/example/example1/balance"    "HASH/CRC32"    "Math/rand") Type Hashbalancestruct{Namestring Ageint}func init () {balance. Registerbalancer ("Hash", &hashbalance{})} Func (P*hashbalance) dobalance (insts []*balance. Instance, Key ...string) (Inst *balance. Instance, err error) {varDefkeystring= Fmt. Sprintf ("%d", Rand. Int ())ifLen (key) >0{Defkey= key[0]} Lens:=Len (insts)ifLENS = =0{Err= Fmt. Errorf ("No Backend Instance")        return} crctable:=CRC32. Maketable (CRC32. IEEE) Hashval:= Crc32. Checksum ([]byte(Defkey), crctable) Index:=int(hashval)%Lens Inst=Insts[index]return}
Hash.go

Golang implementation of a load balancing algorithm (random, polling)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.