实现流程分一下几个步骤
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)
}
}
以下执行效果