321231255 发表于 2016-11-17 09:03:51

高可用高性能负载均衡软件HAproxy详解指南-第一章(简介、...

在Windows/Linux/macOS 下使用命令行开始你的.netcore 之路

准备:

sdk工具:官方提供、最后的latest .NET Core CLI t工具:官方提供

hellow控制台app

using System;
namespace ConsoleApplication
{
   public clss Program
   {
       public static void Main(string[] args)
       {
         Console.WriteLine("Hello World!");
       }
   }
}
$ dotnet new
$ dotnet restore
$ dotnet run

快速开始:
$ dotnet new
创建一个 project.json 文件以完成依赖关系和程序的入口点.

{
    "version": "1.0.0-*",
    "buildOptions": {
      "emitEntryPoint": true
    },
    "dependencies": {
      "Microsoft.NETCore.App": {
            "type": "platform",
            "version": "1.0.0"
      }
    },
   "frameworks": {
      "netcoreapp1.0": {
            "imports": "dnxcore50"
      }
    }
}

Program.cs:

using System;
namespace ConsoleApplication
{
   public class Program
   {
       public static void Main(string[] args)
       {
         Console.WriteLine("Hello World!");
       }
   }
}

$ dotnet restore
分析 project.json 文件, 下载依赖并返回结果。 (或 从一个 cache 机器 grabs ), 写 project.lock.json 文件.
project.lock.json 文件:准许和完成NuGet的graph。 其他工具将读取它,如: dotnet build 和 dotnet run, 即保证用一个正确的方式处理原代码。即: NuGet 依赖和和绑定方案.
$ dotnet run
调用dotnet build 建造运行,调用dotnet来运行应用..

$ dotnet run
Hello, World!

可以用dotnet build 来编译代码:修改 project.json 文件来满足你的要求。
首先删除"type": "platform" 依赖元素. 这个项目仅依赖"Microsoft.NETCore.App".

"dependencies": {
   "Microsoft.NETCore.App": {
       "version": "1.0.0"
   }
},

接着指明一个目标环境的运行节点,.以下为:Windows 1064 位版本 和 Mac OS X 的 10.1版本1

"runtimes": {
"win10-x64": {},
"osx.10.11-x64": {}


$ dotnet restore
$ dotnet build
$ .\bin\Debug\netcoreapp1.0\win10-x64\HelloNative.exe
Hello World!

您会注意到本地应用程序需要长时间build,但运行速度快一些。随着应用程序的增长,变得更加明显。
build 进程产生一些文件. 文件在 bin\Debug\netcoreapp1.0\中,RID 选项是.项目的hellonative.dll,有一个hellonative.exe,它完成运行库加载和启动应用程序。注意,所生成的应用程序的名称被更改,因为项目目录的名称已更改。
您可能希望将此应用程序包,放在网络运行时的机器上执行。请使用DotNet命令发布。 DotNet发布命令创建一个新的子目录。/bin/debug / netcoreapp1.0 / < >目录称为发布平台。它复制可执行文件,所有相关的DLL和框架,可以将该目录复制到另一台机器(或一个容器)并在那里执行应用程序。
以下为:第一个Hello World示例发布。程序是一个可移植的应用程序,默认类型的应用程序。一种便携式应用程序,在目标机器上安装了一个网络核心。便携式应用可以建立在一台机器上,并在任何地方执行。本地应用程序必须单独为每个目标机构建。DotNet发布创建一个目录,应用程序的dll,和任何相关的DLL,不是平台安装部分。
建议program
让我们改变文件一点点。斐波那契数列是有趣的:
Program.cs:

using static System.Console;
namespace ConsoleApplication
{
   public class Program
   {
       public static int FibonacciNumber(int n)
       {
         int a = 0;
         int b = 1;
         int tmp;

         for (int i = 0; i < n; i++)
         {
               tmp = a;
               a = b;
               b += tmp;
         }

         return a;
       }

       public static void Main(string[] args)
       {
         WriteLine("Hello World!");
         WriteLine("Fibonacci Numbers 1-15:");

         for (int i = 0; i < 15; i++)
         {
               WriteLine($"{i+1}: {FibonacciNumber(i)}");
         }
       }
   }
}

开始运行:假设在windows里,项目目录为: Fibonacci:

$ dotnet build
$ .\bin\Debug\netcoreapp1.0\win10-x64\Fibonacci.exe
1: 0
2: 1
3: 1
4: 2
5: 3
6: 5
7: 8
8: 13
9: 21
10: 34
11: 55
12: 89
13: 144
14: 233
15: 377

单一的文件是简单的一次性程序,多个文件有多个组件。多个文件是一种好的方法。 创建一个新的文件,并给它一个唯一的命名空间::

using System;
namespace NumberFun
{
   // code can go here
}
以下是 Program.cs文件:
using static System.Console;
using NumberFun;<< span="">

build它:
$ dotnet build
使新的文件做一些事情            
例如:一个斐波那契序列发生,比如说建立了以前的斐波那契,缓存一些斐波纳中间值和添加一些递归。更好的斐波那契的例子看起来像这样:

using System;
using System.Collections.Generic;

namespace NumberFun
{
   public class FibonacciGenerator
   {
       private Dictionary<int, int>_cache = new Dictionary<int, int>();

       private int Fib(int n) => n < 2 ? n : FibValue(n - 1) + FibValue(n - 2);

       private int FibValue(int n)
       {
         if (!_cache.ContainsKey(n))
         {
               _cache.Add(n, Fib(n));
         }

         return _cache;
       }

       public IEnumerableGenerate(int n)
       {
         for (int i = 0; i < n; i++)
         {
               yield return FibValue(i);
         }
       }
   }
}

注意,使用Dictionary< int,int,int>和IEnumerable均在System.Collections namespace< >系统中。microsoft.netcore.app包是一元软件包,包含了许多NET框架的核心组件。通过包括本元软件包,你已经有system.collections.dll组件作为项目的一部分。你可以通过运行验证这个模块发布和检查是安装包的一部分文件。你会看到列表中的system.collections.dll。

{
"version": "1.0.0-*",
"buildOptions": {
   "debugType": "portable",
   "emitEntryPoint": true
},
"dependencies": {},
"frameworks": {
   "netcoreapp1.0": {
   "dependencies": {
       "Microsoft.NETCore.App": {
         "version": "1.0.0"
       }
   },
   "imports": "dnxcore50"
   }
},
"runtimes": {
   "win10-x64": {},
   "osx.10.11-x64": {}
}
}

调整在Program.cs文件下main()方法、如下所示。假设cs使用System;声明,有一个使用using static System.Console。

public static void Main(string[] args)
{
   var generator = new FibonacciGenerator();
   foreach (var digit in generator.Generate(15))
   {
       WriteLine(digit);
   }
}
完成运行
$ dotnet run
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377

使用文件夹组织代码,通过添加多个文件,确保给他们的命名空间.
/MyProject
|__Program.cs
|__AccountInformation.cs
|__MonthlyReportRecords.cs
|__project.json
当你的项目的规模相对较小,这是伟大的作品。然而,如果你有一个更大的应用程序,有许多不同的数据类型和潜在的多个层,这是文件夹的发挥。你可以创建自己的文件和文件夹。            
/NewTypes
|__/Model
|__Program.cs
|__project.json
增加新的类型到文件夹:
/NewTypes
|__/Model
|__AccountInformation.cs
|__MonthlyReportRecords.cs
|__Program.cs
|__project.json
同一个目录使用同一个明媚空间
Program.cs.
Example: Pet Types
以下为创建两个新类型例子.
Folder Structure:
/NewTypes
|__/Pets
|__Dog.cs
|__Cat.cs
|__IPet.cs
|__Program.cs
|__project.json

IPet.cs:
using System;
namespace Pets
{
   public interface IPet
   {
       string TalkToOwner();
   }
}
Dog.cs:
using System;
namespace Pets
{
   public class Dog : IPet
   {
       public string TalkToOwner() => "Woof!";
   }
}
Cat.cs:
using System;
namespace Pets
{
   public class Cat : IPet
   {
       public string TalkToOwner() => "Meow!";
   }
}
Program.cs:
using System;
using Pets;
using System.Collections.Generic;
namespace ConsoleApplication
{
   public class Program
   {
       public static void Main(string[] args)
       {
         Listpets = new List
         {
               new Dog(),
               new Cat()
         };

         foreach (var pet in pets)
         {
               Console.WriteLine(pet.TalkToOwner());
         }
       }
   }
}
project.json:
{
"version": "1.0.0-*",
"buildOptions": {
   "emitEntryPoint": true
},
"dependencies": {
   "Microsoft.NETCore.App": {
   "type": "platform",
   "version": "1.0.0"
   }
},
"frameworks": {
   "netcoreapp1.0": {
   "imports": "dnxcore50"
   }
}
}

开始运行

$ dotnet restore
$ dotnet run<< span="">

Woof!
Meow!

新的宠物类型可以添加(如鸟),扩展这个项目。
这里有一个很好的方法来做:动源你现有的项目进入了一个新的SRC文件夹。

/Project
|__/src
1.Create a /test directory.
/Project
|__/src
|__/test
2,Create a new global.json file:
/Project
|__/src
|__/test
|__global.json
3.global.json:
{
"projects": [
   "src", "test"
]
}

该文件告诉构建系统,这是一个多项目系统,它允许寻找依赖关系,而不仅仅是当前文件夹中的执行情况。这是很重要的,因为它允许您将依赖于测试项目中的代码放在测试中。 例如:扩展新项目 现在项目系统已就位,您可以创建测试项目并开始编写测试项目!从这里开始,本指南将使用和扩展示例类型项目。此外,它将使用xUnit测试框架。随时按照或创建自己的多项目系统测试。
整个项目结构应该是这样的:   
/NewTypes
|__/src
|__/NewTypes
   |__/Pets
      |__Dog.cs
      |__Cat.cs
      |__IPet.cs
   |__Program.cs
   |__project.json
|__/test
|__NewTypesTests
   |__PetTests.cs
   |__project.json
|__global.json

有两个新的东西,以确保你在你的测试项目:
一个正确的project.json
参考xUnit
参考模块测试xUnit
在测试中对应于代码的命名空间的引用
XUnit测试类。
newtypestests / project.json: :

{
"version": "1.0.0-*",
"testRunner": "xunit",

"dependencies": {
   "Microsoft.NETCore.App": {
   "type":"platform",
   "version": "1.0.0"
   },
   "xunit":"2.2.0-beta2-build3300",
   "dotnet-test-xunit": "2.2.0-preview2-build1029",
   "NewTypes": "1.0.0"
},
"frameworks": {
   "netcoreapp1.0": {
   "imports": [
       "dnxcore50",
       "portable-net45+win8"
   ]
   }
}

PetTests.cs:

using System;
using Xunit;
using Pets;
public class PetTests
{
   
   public void DogTalkToOwnerTest()
   {
       string expected = "Woof!";
       string actual = new Dog().TalkToOwner();

       Assert.Equal(expected, actual);
   }

   
   public void CatTalkToOwnerTest()
   {
       string expected = "Meow!";
       string actual = new Cat().TalkToOwner();

       Assert.Equal(expected, actual);
   }
}}

现在开始测试,请确保在顶级目录
$ dotnet restore
$ cd test/NewTypesTests
$ dotnet test
输出:
xUnit.net .NET CLI test runner (64-bit win10-x64)
Discovering: NewTypesTests
Discovered:NewTypesTests
Starting:    NewTypesTests
Finished:    NewTypesTests
=== TEST EXECUTION SUMMARY ===
NewTypesTestsTotal: 2, Errors: 0, Failed: 0, Skipped: 0, Time: 0.144s
SUMMARY: Total: 1 targets, Passed: 1, Failed: 0.
haproxy 性能特点HAProxy借助于OS上几种常见的技术来实现性能的最大化。

    1、单进程、事件驱动模型显著降低了上下文切换的开销及内存占用。
    2、O(1)事件检查器(event checker)允许其在高并发连接中对任何连接的任何事件实现即时探测。
    3、在任何可用的情况下,单缓冲(single buffering)机制能以不复制任何数据的方式完成读写操作,这会节约大量的CPU时钟周期及内存带宽;
    4、借助于Linux 2.6 (>= 2.6.27.19)上的splice()系统调用,HAProxy可以实现零复制转发(Zero-copy forwarding),在Linux 3.5及以上的OS中还可以实现零复制启动(zero-starting);
    5、MRU内存分配器在固定大小的内存池中可实现即时内存分配,这能够显著减少创建一个会话的时长;
    6、树型存储:侧重于使用作者多年前开发的弹性二叉树,实现了以O(log(N))的低开销来保持计时器命令、保持运行队列命令及管理轮询及最少连接队列;
    7、优化的HTTP首部分析:优化的首部分析功能避免了在HTTP首部分析过程中重读任何内存区域;
    8、精心地降低了昂贵的系统调用,大部分工作都在用户空间完成,如时间读取、缓冲聚合及文件描述符的启用和禁用等;

    所有的这些细微之处的优化实现了在中等规模负载之上依然有着相当低的CPU负载,甚至于在非常高的负载场景中,5%的用户空间占用率和95%的系统空间占用率也是非常普遍的现象,这意味着HAProxy进程消耗比系统空间消耗低20倍以上。因此,对OS进行性能调优是非常重要的。即使用户空间的占用率提高一倍,其CPU占用率也仅为10%,这也解释了为何7层处理对性能影响有限这一现象。由此,在高端系统上HAProxy的7层性能可轻易超过硬件负载均衡设备。

    在生产环境中,在7层处理上使用HAProxy作为昂贵的高端硬件负载均衡设备故障故障时的紧急解决方案也时长可见。硬件负载均衡设备在“报文”级别处理请求,这在支持跨报文请求(request across multiple packets)有着较高的难度,并且它们不缓冲任何数据,因此有着较长的响应时间。对应地,软件负载均衡设备使用TCP缓冲,可建立极长的请求,且有着较大的响应时间。

负载均衡器的性能评估因素

三个重要因素:

1、会话率 :单位时间内的处理的请求数
2、会话并发能力:并发处理能力
3、数据率:处理数据能力

    经过官方测试统计,haproxy 单位时间处理的最大请求数为20000个,可以同时维护40000-50000个并发连接,最大数据处理能力为10Gbps。综合上述,haproxy是性能优越的负载均衡、反向代理服务器。

安装HAproxy

1、安装haproxy

# yum -y groupinstall "Development Tools"
# yum -y install haproxy

2、配置文件

# rpm -ql haproxy
/etc/haproxy   #配置文件目录
/etc/haproxy/haproxy.cfg   #配置文件
/usr/lib/systemd/system/haproxy.service    #启动脚本
/usr/sbin/haproxy    #haproxy 命令
/usr/share/man/man1/haproxy.1.gz #man 文档

3、默认配置文件

# cat haproxy.cfg
#---------------------------------------------------------------------
# Example configuration for a possible web application.See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt#官方配置文档,很详细,英文没问题的博友,可以看看
#
#---------------------------------------------------------------------
#---------------------------------------------------------------------
# Global settings #全局配置文件
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:#配置日志
    #
    # 1) configure syslog to accept network log events.This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog #修改syslog配置文件
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog#定义日志设备
    #
    #    local2.*                     /var/log/haproxy.log
    #
    log         127.0.0.1 local2 #
#全局的日志配置 其中日志级别是
#local0 是日志设备,必须为如下24种标准syslog设备的一种:
#kern user mail daemon auth syslog lpr news
#uucp cron auth2 ftp ntp audit alert cron2
#local0 local1 local2 local3 local4 local5 local6 local7
    chroot      /var/lib/haproxy
    pidfile   /var/run/haproxy.pid #将所有进程的pid写入文件启动进程的用户必须有权限访问此文件。
    maxconn   4000 #最大连接数,默认4000
    user      haproxy #用户
    group       haproxy #组
    daemon ##创建1个进程进入deamon模式运行。此参数要求将运行模式设置为"daemon"
    # turn on stats unix socket#unix socket 文件
    stats socket /var/lib/haproxy/stats
#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block#默认的全局设置,这些参数可以被利用配置到frontend,backend,listen组件
#---------------------------------------------------------------------
defaults
    mode                  http#默认的模式mode { tcp|http|health },tcp是4层,http是7层,health只会返回OK
    log                     global #采用全局定义的日志
    option                  httplog #日志类别http日志格式
    option                  dontlognull #不记录健康检查的日志信息
    option http-server-close #每次请求完毕后主动关闭http通道
    option forwardfor       except 127.0.0.0/8 #不记录本机转发的日志
    option                  redispatch #serverId对应的服务器挂掉后,强制定向到其他健康的服务器
    retries               3 #3次连接失败就认为服务不可用,也可以通过后面设置
    timeout http-request    10s#请求超时
    timeout queue         1m #队列超时
    timeout connect         10s #连接超时
    timeout client          1m #客户端连接超时
    timeout server          1m #服务器连接超时
    timeout http-keep-alive 10s #长连接超时
    timeout check         10s#检查超时
    maxconn               3000 #最大连接数
#---------------------------------------------------------------------
# main frontend which proxys to the backends #frontend 与backends代理配置
#---------------------------------------------------------------------
frontendmain *:5000
#acl策略配置
    acl url_static       path_beg       -i /static /images /javascript /stylesheets
    acl url_static       path_end       -i .jpg .gif .png .css .js
    use_backend static          if url_static#满足策略要求,则响应策略定义的backend页面
    default_backend             app #不满足则响应backend的默认页面
#---------------------------------------------------------------------
# static backend for serving up images, stylesheets and such #定义使用静态后端图像,样式表等
#---------------------------------------------------------------------
backend static
    balance   roundrobin #负载均衡模式轮询
    server      static 127.0.0.1:4331 check #服务器定义
#---------------------------------------------------------------------
# round robin balancing between the various backends
#---------------------------------------------------------------------
backend app
    balance   roundrobin #负载均衡模式轮询
    serverapp1 127.0.0.1:5001 check #服务器定义,check进行健康检查
    serverapp2 127.0.0.1:5002 check
    serverapp3 127.0.0.1:5003 check
    serverapp4 127.0.0.1:5004 check

案例:实现web负载

1、node1安装http和测试页面# yum -y install httpd
# cd /var/www/html/
# echo "<h1>Server WWW node1</h1>" > index.html

2、node2安装http和测试页面

# yum -y install httpd
# cd /var/www/html/
# echo "<h1>Server WWW node2</h1>" > index.html

3、haproxy安装配置

# yum -y groupinstall "Development Tools"
# yum -y install haproxy

4、配置文件

# cat /etc/haproxy/haproxy.cfg
......主要配置函数
listen stats   #监控页面
    mode http
    bind 0.0.0.0:1080
    stats enable
    stats hide-version
    stats uri   /haproxyadmin?stats
    stats realm   Haproxy\ Statistics
    stats auth    admin:admin
    stats admin if TRUE
frontend main#定义服务器组
    bind *:80
    default_backend server
backend server#定义服务器
    mode http
    balance roundrobin
    option httpchk HEAD /index.html HTTP/1.0
    server node1 192.168.211.140:80 cookie 1 weight 5 check inter 2000 rise 1 fall 1
    server node2 192.168.211.128:80 cookie 1 weight 5 check inter 2000 rise 1 fall 1

5、查看监控页面6、测试



页: [1]
查看完整版本: 高可用高性能负载均衡软件HAproxy详解指南-第一章(简介、...