golang高性能网络编程框架-Netpoll(字节开源)

内容纲要

简介

Netpoll是一款高性能NIO网络库,由golang开发专注于RPC场景。

功能特性

file

个人觉得唯一的遗憾就是不支持Windows,Windows的相关接口实现都是return nil,让我这个Windows小用户只能将程序发布到Linux上去测试。

跟着官方跑Demo

让我们来一起跟着官网来编写一个Server和Client端吧。

工程结构

  1. vscode目录结构
    file

  2. 文本目录结构

    
    D:.
    │  docker-compose.yaml docker-compse启动两个端
    │
    ├─echo-client 客户端
    │      Dockerfile 
    │      go.mod
    │      go.sum
    │      netpoll_echo_client.go
    │
    └─echo-server 服务端
        Dockerfile
        go.mod
        go.sum
        netpoll_echo_server.go
3. 说明
因为netpoll不支持Windows所以我们使用DockerDesktop在Linux环境中运行。

## Server端
### Server端go源码(netpoll_echo_server.go)
```java

package main

import (
    "context"
    "fmt"
    "time"

    "github.com/cloudwego/netpoll"
)

func main() {
    network, address := "tcp", ":8080"
    listener, _ := netpoll.CreateListener(network, address)

    eventLoop, _ := netpoll.NewEventLoop(
        handle,
        netpoll.WithOnPrepare(prepare),
        netpoll.WithOnConnect(connect),
        netpoll.WithReadTimeout(time.Second),
    )

    fmt.Println("Start server and listening on 8080.")

    // start listen loop ...
    eventLoop.Serve(listener)
}

var _ netpoll.OnPrepare = prepare
var _ netpoll.OnConnect = connect
var _ netpoll.OnRequest = handle
var _ netpoll.CloseCallback = close

func prepare(connection netpoll.Connection) context.Context {
    return context.Background()
}

func close(connection netpoll.Connection) error {
    fmt.Printf("[%v] connection closed\n", connection.RemoteAddr())
    return nil
}

func connect(ctx context.Context, connection netpoll.Connection) context.Context {
    fmt.Printf("[%v] connection established\n", connection.RemoteAddr())
    connection.AddCloseCallback(close)
    return ctx
}

func handle(ctx context.Context, connection netpoll.Connection) error {
    reader, writer := connection.Reader(), connection.Writer()
    defer reader.Release()

    msg, _ := reader.ReadString(reader.Len())
    fmt.Printf("[recv msg] %v\n", msg)

    writer.WriteString(msg)
    writer.Flush()

    return nil
}

go mod文件

go mod文件直接进入目录使用go mod命令生成即可,命令如下:

cd echo-server
go mod init echo-server

Dockerfile


FROM golang:1.21

# Set destination for COPY
WORKDIR /app

# Download Go modules
COPY go.mod go.sum ./
RUN go mod download

# Copy the source code. Note the slash at the end, as explained in
# https://docs.docker.com/reference/dockerfile/#copy
COPY  . ./

# Build
RUN CGO_ENABLED=0 GOOS=linux go build -o echo-client
# Run
CMD ["./echo-client"]

Client端

Server端go源码(netpoll_echo_client.go)

FROM golang:1.21

# 工作目录
# Set destination for COPY
WORKDIR /app

# Download Go modules
COPY go.mod go.sum ./
RUN go mod download

# Copy the source code. Note the slash at the end, as explained in
# https://docs.docker.com/reference/dockerfile/#copy
COPY  . ./

# Build
RUN CGO_ENABLED=0 GOOS=linux go build -o echo-server

RUN ls -al

# Optional:
# To bind to a TCP port, runtime parameters must be supplied to the docker command.
# But we can document in the Dockerfile what ports
# the application is going to listen on by default.
# https://docs.docker.com/reference/dockerfile/#expose
EXPOSE 8080

# Run
CMD ["./echo-server"]

go mod文件

与Server端处理一样,使用go mod命令生成


cd echo-client
go mod init echo-client

Dockerfile

FROM golang:1.21

# Set destination for COPY
WORKDIR /app

# Download Go modules
COPY go.mod go.sum ./
RUN go mod download

# Copy the source code. Note the slash at the end, as explained in
# https://docs.docker.com/reference/dockerfile/#copy
COPY  . ./

# Build
RUN CGO_ENABLED=0 GOOS=linux go build -o echo-client
# Run
CMD ["./echo-client"]

Docker Compose yaml文件

version: '3.8'  

services:
  echo-server:
    image: echo-server:latest  
    ports:
      - "8080:8080"  
    restart: always  

  echo-client:
    image: echo-client:latest  
    restart: always  

运行

让Server和Client跑起来

这里还是推荐个人学习安装一个DockerDesktop在自己的计算机中,我这儿使用DockerDesktop。


docker-compose -f docker-compose up -d

file

服务端与客户端容器启动成功:
file

客户端与服务端通信日志

  1. Server端日志
    file

  2. Client端日志
    file

结语

netpoll的高性能和易于使用,建议RPC类的需求都可以使用这个库,除了Windows。大家不妨一试。

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部