2 Star 9 Fork 1

os-lee/easy-paas

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
load_balancer.go 1.82 KB
一键复制 编辑 原始数据 按行查看 历史
lee 提交于 2024-07-11 15:01 . websocket路由支持url重写,负载均衡
package load_balancer
import (
"errors"
"fmt"
"gitee.com/os-lee/easy-paas/common"
"gitee.com/os-lee/easy-paas/common/discovery"
"gitee.com/os-lee/easy-paas/gateway/internal/dao"
"net/http"
"net/url"
"sync"
)
type Server struct {
URL *url.URL
Weight int // 权重,用于权重负载均衡
}
// Balancer 接口定义了所有负载均衡策略都应实现的公共方法
type Balancer interface {
Pick(*http.Request) *Server
}
type BaseBalancer struct {
servers []Server
mu sync.RWMutex
}
// Handler 各个业务的负载均衡器
var Handler *LoadBalancer
func init() {
Handler = newLoadBalancer()
}
type LoadBalancer struct {
// key:ServiceName val:load_balancer.Balancer
LoadBalancerMap sync.Map
}
func newLoadBalancer() *LoadBalancer {
return &LoadBalancer{
LoadBalancerMap: sync.Map{},
}
}
func (l *LoadBalancer) Get(service *dao.ServiceDetail) (Balancer, error) {
key := service.Info.ServiceName
if value, ok := l.LoadBalancerMap.Load(key); ok {
return value.(Balancer), nil
}
// 服务发现
rMsgs, err := discovery.EtcdCli.DiscoverServices(service.LoadBalance.ProxyName)
if err != nil || len(rMsgs) == 0 {
msg := fmt.Sprintf("没有可用的地址,服务名: %s, 被代理名: %s, err:%v",
service.Info.ServiceName, service.LoadBalance.ProxyName, err)
return nil, errors.New(msg)
}
var servers []Server
for _, msg := range rMsgs {
server := Server{
URL: common.MustParseURL(common.ProtocolConverter(msg.ServiceProtocolCode) + msg.ServiceAddr),
Weight: 1,
}
servers = append(servers, server)
}
// 获取负载均衡器
lb := new(Factory).Produce(service.LoadBalance.RoundType, servers)
l.LoadBalancerMap.Store(key, lb)
return lb, err
}
func (l *LoadBalancer) Update(serviceName string) {
// 直接删除即可,获取时会重新创建
l.LoadBalancerMap.Delete(serviceName)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/os-lee/easy-paas.git
git@gitee.com:os-lee/easy-paas.git
os-lee
easy-paas
easy-paas
6cf1638f64c0

搜索帮助