本篇文章為大家展示了怎么在golang中實現負載均衡,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
golang是一種編譯語言,可以將代碼編譯為機器代碼,編譯后的二進制文件可以直接部署到目標機器而無需額外的依賴,所以golang的性能優于其他的解釋性語言,且可以在golang中使用goroutine來實現并發性,它提供了一個非常優雅的goroutine調度程序系統,可以很容易地生成數百萬個goroutine。
package balance
type Instance struct {
host string
port int
}
func NewInstance(host string, port int) *Instance {
return &Instance{
host: host,
port: port,
}
}
func (p *Instance) GetHost() string {
return p.host
}
func (p *Instance) GetPort() int {
return p.port
}package balance
type Balance interface {
/**
*負載均衡算法
*/
DoBalance([] *Instance,...string) (*Instance,error)
}package balance
import (
"errors"
"math/rand"
)
func init() {
RegisterBalance("random",&RandomBalance{})
}
type RandomBalance struct {
}
func (p *RandomBalance) DoBalance(insts [] *Instance,key...string) (inst *Instance, err error) {
if len(insts) == 0 {
err = errors.New("no instance")
return
}
lens := len(insts)
index := rand.Intn(lens)
inst = insts[index]
return
}roundrobin.go
package balance
import (
"errors"
)
func init() {
RegisterBalance("round", &RoundRobinBalance{})
}
type RoundRobinBalance struct {
curIndex int
}
func (p *RoundRobinBalance) DoBalance(insts [] *Instance, key ...string) (inst *Instance, err error) {
if len(insts) == 0 {
err = errors.New("no instance")
return
}
lens := len(insts)
if p.curIndex >= lens {
p.curIndex = 0
}
inst = insts[p.curIndex]
p.curIndex++
return
}package balance
import (
"fmt"
)
type BalanceMgr struct {
allBalance map[string]Balance
}
var mgr = BalanceMgr{
allBalance: make(map[string]Balance),
}
func (p *BalanceMgr) registerBalance(name string, b Balance) {
p.allBalance[name] = b
}
func RegisterBalance(name string, b Balance) {
mgr.registerBalance(name, b)
}
func DoBalance(name string, insts []*Instance) (inst *Instance, err error) {
balance, ok := mgr.allBalance[name]
if !ok {
err = fmt.Errorf("not fount %s", name)
fmt.Println("not found ",name)
return
}
inst, err = balance.DoBalance(insts)
if err != nil {
err = fmt.Errorf(" %s erros", name)
return
}
return
}下面進行測試:
func main() {
var insts []*balance.Instance
for i := 0; i < 10; i++ {
host := fmt.Sprintf("192.168.%d.%d", rand.Intn(255), rand.Intn(255))
port, _ := strconv.Atoi(fmt.Sprintf("880%d", i))
one := balance.NewInstance(host, port)
insts = append(insts, one)
}
var name = "round"
if len(os.Args) > 1 {
name = os.Args[1]
}
for {
inst, err := balance.DoBalance(name, insts)
if err != nil {
fmt.Println("do balance err")
time.Sleep(time.Second)
continue
}
fmt.Println(inst)
time.Sleep(time.Second)
}
}package add
import (
"awesomeProject/test/balance"
"fmt"
"math/rand"
"hash/crc32"
)
func init() {
balance.RegisterBalance("hash", &HashBalance{})
}
type HashBalance struct {
key string
}
func (p *HashBalance) DoBalance(insts [] *balance.Instance, key ...string) (inst *balance.Instance, err error) {
defKey := fmt.Sprintf("%d", rand.Int())
if len(key) > 0 {
defKey = key[0]
}
lens := len(insts)
if lens == 0 {
err = fmt.Errorf("no balance")
return
}
hashVal := crc32.Checksum([]byte(defKey), crc32.MakeTable(crc32.IEEE))
index := int(hashVal) % lens
inst = insts[index]
return
}這樣就能交給管理器統一管理了,而且不會影響原來的api。
補充:golang grpc配合nginx實現負載均衡
grpc負載均衡有主要有進程內balance, 進程外balance, proxy 三種方式,本文敘述的是proxy方式,以前進程內的方式比較流行,靠etcd或者consul等服務發現來輪詢,隨機等方式實現負載均衡。
現在nginx 1.13過后正式支持grpc, 由于nginx穩定,高并發量,功能強大,更難能可貴的是部署方便,并且不像進程內balance那樣不同的語言要寫不同的實現,因此我非常推崇這種方式。
確認安裝版本大于1.13的nginx后打開配置文件,寫入如下配置
upstream lb{
#負載均衡的grpc服務器地址
server 127.0.0.1:50052;
server 127.0.0.1:50053;
server 127.0.0.1:50054;
#keepalive 500;#這個東西是nginx和rpc服務器群保持長連接的總數,設置可以提高效率,同時避免nginx到rpc服務器之間默認是短連接并發過后造成time_wait過多
}
server {
listen 9527 http2;
access_log /var/log/nginx/host.access.log main;
http2_max_requests 10000;#這里默認是1000,并發量上來會報錯,因此設置大一點
#grpc_socket_keepalive on;#這個東西nginx1.5過后支持
location / {
grpc_pass grpc://lb;
error_page 502 = /error502grpc;
}
location = /error502grpc {
internal;
default_type application/grpc;
add_header grpc-status 14;
add_header grpc-message "Unavailable";
return 204;
}
}可以在host.access.log日志文件里面看到數據轉發記錄
syntax = "proto3"; // 指定proto版本
package grpctest; // 指定包名
// 定義Hello服務
service Hello {
// 定義SayHello方法
rpc SayHello(HelloRequest) returns (HelloReply) {}
}
// HelloRequest 請求結構
message HelloRequest {
string name = 1;
}
// HelloReply 響應結構
message HelloReply {
string message = 1;
}客戶端連接地址填寫nginx的監聽地址,相關代碼如下:
package main
import (
pb "protobuf/grpctest" // 引入proto包
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
"fmt"
"time"
)
const (
// Address gRPC服務地址
Address = "127.0.0.1:9527"
)
func main() {
// 連接
conn, err := grpc.Dial(Address, grpc.WithInsecure())
if err != nil {
grpclog.Fatalln(err)
}
defer conn.Close()
// 初始化客戶端
c := pb.NewHelloClient(conn)
reqBody := new(pb.HelloRequest)
reqBody.Name = "gRPC"
// 調用方法
for{
r, err := c.SayHello(context.Background(), reqBody)
if err != nil {
grpclog.Fatalln(err)
}
fmt.Println(r.Message)
time.Sleep(time.Second)
}
}package main
import (
"net"
"fmt"
pb "protobuf/grpctest" // 引入編譯生成的包
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
const (
// Address gRPC服務地址
Address = "127.0.0.1:50052"
//Address = "127.0.0.1:50053"
//Address = "127.0.0.1:50054"
)
var HelloService = helloService{}
type helloService struct{}
func (this helloService) SayHello(ctx context.Context,in *pb.HelloRequest)(*pb.HelloReply,error){
resp := new(pb.HelloReply)
resp.Message = Address+" hello"+in.Name+"."
return resp,nil
}
func main(){
listen,err:=net.Listen("tcp",Address)
if err != nil{
grpclog.Fatalf("failed to listen: %v", err)
}
s:=grpc.NewServer()
pb.RegisterHelloServer(s,HelloService)
grpclog.Println("Listen on " + Address)
s.Serve(listen)
}以50052,50053,50054 3個端口啟3個服務端進程,運行客戶端代碼,即可看見如下效果:

上述內容就是怎么在golang中實現負載均衡,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。