负载均衡算法之加权随机算法的简单实现

表妹要我教她负载均衡算法 一、随机法(Random) 完全随机:通过系统的随机算法,根据后端服务器的列表大小值来随机选取其中的一台服务器进行访问。由概率统计理论可以得知,随着客户端调用服务端的次数增多,其实际效果越来越接近于平均分配调用量到后端的每一台服务器,也就是轮询的结果。 代码实现: public class Servers { public List<String> list = new ArrayList<>() { { add("192.168.1. 阅读详情

1、我们在前面写过“随机算法”来实现简单的负载均衡。
https://blog.youkuaiyun.com/github_26672553/article/details/99701928

用过nginx配置负载均衡,可能会写过类似这样的配置:

upstream lb {
	server xxxxxx1 weight=1
	server xxxxxx2 weight=2
}

这表示server1和server2的比重为1:2

2、在go里我们也可以简单实现

#以1:2为例,我们构建一个切片
[011]
#然后随机去一个索引

3、下面开始具体实现
要给HttpServer服务添加权重配置,那么首先需要修改下面代码:

//目标server类
type HttpServer struct {
   
   
	Host   string
	Weight int
}

//初始化HttpServer对象
func NewHttpServer(host string, weight int) *HttpServer {
   
   
	return &HttpServer{
   
   Host: host, Weight: weight}
}

这样在创建server的时候传递weight参数作为权重参数:NewHttpServer("http://localhost:9091", 1)

4、包里有个init()函数,当引入包的时候会自动执行此函数。
我们整理一下代码:把添加httpserver和用于实现权重分配的切片的创建都写在这个函数里:

//定义负载均衡对象
var LB *LoadBalance

// 定义用于之后加权随机计算的切片
var ServerIndices []int

//引入这个包就会自动执行这个函数
func init() {
   
   
	LB = NewLoadBalance()
	//给其添加2个服务
	//这里写死,常规做法是引入配置文件
	LB.AddServer(NewHttpServer("http://localhost:9091", 1))
	LB.AddServer(NewHttpServer("http://localhost:9092", 2))

	//下面代码实现了 [0 1 1]
	//9091这个httpServer权重为1,9092这个httpServer权重为2
	for index, server := range  LB.Servers{
   
   
		if server.Weight > 0 {
   
   
			for i := 0; i < server.Weight; i++ {
   
   
				ServerIndices = append(ServerIndices, index)
			}
		}
	}

	fmt.Println(ServerIndices)	//[0 1 1]
}

这段代码是核心,首先是创建负载均衡对象,然后往里添加server,最后循环取出server根本权重值组装[0 1 1]这样的切片。

4、下面就是加权随机算法,也就是先从ServerIndices切片中随机取索引,然后根据索引取出ServerIndices切片的值,然后把该值作为多个server的索引,取出一个server。


//加权随机算法
func (this *LoadBalance) 
Java加权负载均衡策略实现过程解析 主要介绍了Java加权负载均衡策略实现过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 立即下载

相关推荐

Vanna 2.0:基于LLM的智能文本到SQL框架,实现企业级数据查询与权限控制

文本到SQL技术是自然语言处理与数据库交互的重要桥梁,它允许用户使用日常语言直接查询数据库,无需编写复杂的SQL语句。其核心原理是利用大语言模型理解用户意图,并结合检索增强生成技术,将自然语言问题转换为准确的结构化查询语言。这项技术的价值在于大幅降低了数据访问门槛,提升了业务人员的数据自助分析能力,并能在金融分析、销售报表、运营监控等场景中实现实时数据洞察。Vanna 2.0作为一个开源框架,通过引入用户感知的智能体架构和行级安全策略,解决了企业级应用中的多租户数据隔离与权限控制等关键问题,使得自然语言数据

weixin_42629522的博客 543

UWB学习——day4

总的来说,BPM-BPSK调制方案是一种利用脉冲位置和相位来编码信息的高效数字调制技术,特别适用于UWB通信系统,以实现高速数据传输和频谱效率。这种方式将时间和相位综合使用,从而提高了数据传输的容量。总之,超外差结构是一种接收器设计,通过将不同频率的信号转换到一个共同的中间频率来提高信号选择性和抗干扰性。超外差结构是一种用于接收器的电子电路设计,它的目标是从无线信号中提取有用的信息,比如音频、数据或图像。该芯片的接收机是超外差结构,所谓超外差结构一种基于频率转换的接收器架构,旨在提高信号选择性和抗干扰性。

许帅的博客 2552

CocosCreator视频播放黑屏?手把手教你封装VideoPlayer组件解决Web环境问题

本文针对Cocos Creator在Web环境下视频播放黑屏等常见问题,提供了一套工程化的VideoPlayer组件封装解决方案。文章深入剖析了浏览器自动播放策略、DOM样式隔离等核心挑战,并手把手教你实现一个健壮的管理器,涵盖兼容性处理、性能优化与内存管理,确保视频播放稳定流畅。

plum99的博客 598

ROS 2 Jazzy与Gazebo Harmonic仿真实战:从零搭建机器人仿真环境与高级应用

本文详细介绍了如何使用ROS 2 Jazzy和Gazebo Harmonic从零搭建机器人仿真环境,涵盖环境配置、传感器集成、多机器人协同和GPU加速优化等高级应用。通过实战案例和性能调优技巧,帮助开发者高效构建可靠的机器人仿真系统,提升开发效率。

h9j8k7l6m5n的博客 1217

MFC 修改CheckBox的文本颜色方法

设置主题 这一步是必须的,不可省略。 BOOL CMFCApplication1Dlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 // 设置主题 HWND

Kim的博客 2248

Python爬虫实战:使用Scrapy+Playwright高效爬取全球专利数据库

本文将详细介绍如何使用Python最新技术栈(Scrapy+Playwright)构建一个高效的专利数据库爬虫系统。我们将从爬虫基础知识讲起,逐步深入到反爬应对策略、分布式爬虫架构以及数据存储方案,最终实现一个完整的专利数据采集系统。专利数据是技术创新领域的重要信息资源,包含技术描述、权利要求、申请人信息等宝贵数据。中国国家知识产权局(CNIPA)美国专利商标局(USPTO)欧洲专利局(EPO)世界知识产权组织(WIPO)

2201_76125261的博客 1382

《SAP FICO系统配置从入门到精通共40篇》030、集成配置:FI与生产计划(PP)的自动科目确定

FI和PP的自动科目确定,本质上是把生产业务翻译成会计语言。翻译规则就藏在那些配置表里。配的时候多想一步:这个业务动作,在财务眼里是什么?是材料消耗?是产出入库?还是工费分摊?想清楚这个,再看配置界面,那些代码就不是天书了。最好的测试方式,是月底关账前,让生产部门跑一遍所有类型的生产订单。配置对不对,业务最知道。

985大学毕业,前某大厂员工,啥都会点的程序员! 573

基于STM32、HAL库的MCP4651-503E/ST数字电位器驱动程序设计

@param channel: 通道 (0: A通道, 1: B通道)* @param channel: 通道 (0: A通道, 1: B通道)// SPI1 SCK/MISO/MOSI引脚配置。* @param hmcp: MCP4651句柄。* @param hmcp: MCP4651句柄。* @param hmcp: MCP4651句柄。* @param hmcp: MCP4651句柄。* @param hmcp: MCP4651句柄。* @param hspi: SPI句柄。

corlin6688的博客 136

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

上一篇: 负载均衡算法之ip_hash简单应用
下一篇: 简易http服务健康检查:http服务定时检查、修改状态
学习笔记666
博客等级 码龄12年 1047粉丝 1369原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值