httpfasthttp

设置net.Dialer

net.Dialernet.DialerJavaHttpClientorg.apache.http.impl.conn.PoolingHttpClientConnectionManager
// clients 初始化请求客户端
// @Description:
// @return fhttp.Client
func clients() http.Client {
 dialer := &net.Dialer{
  Timeout: 1 * time.Second,
 }

 return http.Client{
  Timeout: time.Duration(5) * time.Second, //超时时间
  Transport: &http.Transport{
   MaxIdleConnsPerHost:   200,   //单个路由最大空闲连接数
   MaxConnsPerHost:       10000, //单个路由最大连接数
   IdleConnTimeout:       90 * time.Second,
   TLSHandshakeTimeout:   10 * time.Second,
   ExpectContinueTimeout: 1 * time.Second,
   DialContext:           dialer.DialContext,
  },
 }
}

奇怪的知识点

net/http

简单设置的方法如下:

 dialer := &net.Dialer{
  Timeout: 1 * time.Second,
 }
 dialer.Resolver = &net.Resolver{
  Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
   return dialer.DialContext(ctx, "tcp", "114.114.114.114:53") // 通过tcp请求nameserver解析域名
  },
 }

其他设置项同上。

自定义net.Dialer

http.TransportDialContextfunc(ctx context.Context, network, addr string) (net.Conn, error)

下面这个例子我设置了两个IP来测试负载均衡(下期出文字版和视频版)。

DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
    host, port, err := net.SplitHostPort(address)
    if err != nil {
     return nil, err
    }
    //通过自定义nameserver获取域名解析的IP
    //ips, _ := dialer.Resolver.LookupHost(ctx, host)
    //for _, s := range ips {
    // log.Println(s)
    //}

    // 创建链接
    if host == "fun.tester" {
     ip := "127.0.0.1"
     log.Println(ip)
     conn, err := dialer.DialContext(ctx, network, ip+":"+port)
     if err == nil {
      return conn, nil
     }
    }
    return dialer.DialContext(ctx, network, address)
   },
nameserver

测试

测试用例如下:

// TestFaast
// @Description: 测试自定义DNS解析功能
// @param t
func TestFaast(t *testing.T) {
 url := "http://fun.tester:12345/test"
 get := fhttp.Get(url, nil)
 //for i := 0; i < 10; i++ {
 // //go log.Println(string(fhttp.Response(get)))
 // go func() {
 //  log.Println(string(fhttp.Response(get)))
 // }()
 //}
 response := fhttp.Response(get)
 log.Println(string(response))
}

控制台输出:

=== RUN   TestFaast
2022/02/07 15:34:47 127.0.0.1
2022/02/07 15:34:48 Have Fun ~ Tester !
--- PASS: TestFaast (0.31s)
PASS

测试服务

moco_FunTester
    static void main(String[] args) {
        def util = new ArgsUtil(args)
        def server = getServerNoLog(util.getIntOrdefault(0, 12345))
        server.response(delay(textRes("Have Fun ~ Tester !"), 100))
        def run = run(server)
        waitForKey("fan")
        run.stop()
    }