使用golang实现一个简易的http负载均衡器

实现流程分一下几个步骤

1. 监听一个端口以接收客户端的请求。
2. 根据某种策略(如轮询、随机、权重等)将请求转发到后端服务器。
3. 处理后端服务器的响应并返回给客户端。

import (
	"fmt"
	"net/http"
	"net/http/httputil"
	"net/url"
	"sync"
)

// 负载均衡器
type ServerPool struct {
	servers []*url.URL
	current int
	mu      sync.Mutex
}

// 初始化一个新的ServerPool
func NewServerPool(urls []string) (*ServerPool, error) {
	pool := &ServerPool{}
	for _, u := range urls {
		parsedURL, err := url.Parse(u)
		if err != nil {
			return nil, err
		}
		pool.servers = append(pool.servers, parsedURL)
	}
	return pool, nil
}

// 轮询算法获取下一个执行转发的服务器地址
func (p *ServerPool) NextServer() *url.URL {
	p.mu.Lock()
	defer p.mu.Unlock()
	next := p.current
	p.current = (p.current + 1) % len(p.servers)
	return p.servers[next]
}

// 转发请求后端服务器
func ReverseProxyHandler(pool *ServerPool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		serverURL := pool.NextServer()
		proxy := httputil.NewSingleHostReverseProxy(serverURL)
		proxy.ServeHTTP(w, r)
	}
}

func main() {

	// 后端的服务地址
	serverURLs := []string{
		"http://localhost:8001",
		"http://localhost:8002",
		"http://localhost:8003",
	}

	pool, err := NewServerPool(serverURLs)
	if err != nil {
		fmt.Println("Error creating server pool:", err)
		return
	}

	proxyHandler := ReverseProxyHandler(pool)

	http.HandleFunc("/", proxyHandler)

	fmt.Println("Load balancer listening on :8080")

	if err := http.ListenAndServe(":8080", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

以下执行效果
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值