ip_hash

ip_hash

 什么是ip_hash?

  • ip_hash是根据用户请求过来的ip,然后映射成hash值,然后分配到一个特定的服务器里面;
  • 使用ip_hash这种负载均衡以后,可以保证用户的每一次会话都只会发送到同一台特定的服务器里面,它的session不会跨到其他的服务器里面去的;

hash原理

  • 首先通过将ip地址映射成一个hash值,然后将hash值对server的数量3取模,得到server的索引0、1、2;
  • 比如:5%3=2,则把这个请求发送到server3服务器,以此类推;
  • 这样一来,只要用户的IP不发生改变,当前用户的会话就能够一直保持;
function HashCode(const val: String): Integer;
var
  LResult: UInt32;
  I: Integer;
begin
  LResult := 0;
  for I := 1 to Length(val) do
  begin
    LResult := (LResult shl 5) or (LResult shr 27);
    LResult := LResult xor UInt32(val[I]);
  end;
  Result := LResult;
end;

function IpHash(const ip: string; const count: Integer): Integer;
begin
  Result := HashCode(ip) mod count;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  var i: Integer;
  var cnt: Integer := 3;
  Memo1.Lines.Add(IpHash('192.168.19.129', cnt).ToString);
  Memo1.Lines.Add(IpHash('192.168.19.169', cnt).ToString);
  Memo1.Lines.Add(IpHash('192.168.19.10', cnt).ToString);
end;

 

 



 

posted @ 2022-11-07 08:30  delphi中间件  阅读(522)  评论(0编辑  收藏  举报