1 Star 2 Fork 0

hubert-樂xx / xnet

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
LGPL-3.0

以http为基础协议的多协议框架

基于HTTP协议,扩展X-Upgrade头部的多协议MVC执行库

安装教程

<dependency>
    <groupId>cn.xnatural</groupId>
    <artifactId>xnet</artifactId>
    <version>1.2.2</version>
</dependency>

(必须)打包编译(保留方法参数名, 非arg0/arg1...)

maven

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <!-- 编译时保留方法参数名 -->
        <parameters>true</parameters>
    </configuration>
</plugin>

gradle

compileJava {
    options.compilerArgs << '-parameters'
}

compileGroovy {
    groovyOptions.parameters = true
}

HTTP: web服务

XNet xNet = new XNet(":8080");
xNet.http().chain()
        // 添加控制层
        .resolve(
                new TestCtrl(), new MainCtrl()
        )
        // 手动添加路由
        .get("/a/b/{c}", ctx -> {
            ctx.render("c=" + ctx.param("c"));
        });
        .post("/a/b/{c}", ctx -> {
            ctx.render("c=" + ctx.param("c"));
        });
xNet.start();

控制层例子

@Route(path = "test", protocol = "HTTP")
public class TestCtrl {

  // 支持get,post,put多种方法, /test/cus?p1=aa&p2=bb
  @Route(path = "cus")
  ApiResp form(Integer p1, Integer p2, HttpContext ctx) {
    return ApiResp.ok(ctx.request().getFormParams());
  }


  // 接收form 表单提交. /test/form?p1=aa&p2=bb
  @Route(path = "form", consume = "application/x-www-form-urlencoded")
  ApiResp form(Integer p1, String p2, HttpContext ctx) {
    return ApiResp.ok(ctx.request().getFormParams());
  }

  // json 参数
  @Route(path = "json", consume = "application/json", method = "post")
  ApiResp json(HttpContext ctx) {
    return ApiResp.ok(ctx.request().getJsonParams());
  }

  // 手动响应(方便异步处理)
  @Route(path = "async")
  void async(String p1, HttpContext ctx) {
    ctx.render(
            ApiResp.ok("p1: " + p1 + ", " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()))
    );
  }

  // 文件上传
  @Route(path = "upload", method = "post")
  ApiResp upload(FileData file, String version) throws Exception {
    if (file == null) return ApiResp.fail("文件未上传");
    File uploadDir = new File("./upload");
    uploadDir.mkdirs();
    file.transferTo(uploadDir);
    log.info("upload file: " + file);
    return ApiResp.ok().attr("file", file.toString()).attr("version", version);
  }

  // 下载文件, 路径变量, 自定义响应头
  @Route(path = "download/{fName}", method = "get")
  File download(String fName, HttpContext ctx) throws IOException {
    ctx.response.contentDisposition("attachment;filename=" + f.getName());
    return new File("./upload/" + fName);
  }
}

websocket

final Set<WebSocket> wss = ConcurrentHashMap.newKeySet();


public void wsBroadcast(String msg) {
    wss.forEach(ws -> ws.send(msg));
}


@WS(path = "msg")
public void wsReceive(WebSocket ws) {
    log.info("WS connect. {}, {}", ws.request.getCookie("sessionId"), ws.getSession().getRemoteAddress());
    ws.listen(new WsListener() {
      @Override
      public void onClose(WebSocket wst) { 
          wss.remove(wst); 
      }
      
      @Override
      public void onText(String msg) {
        log.info("test ws receive client msg: {}", msg);
      }
      
      @Override
      public void onBinary(byte[] msg) {
      
      }
    });
    wsBroadcast("上线: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    wss.add(ws);
}

X-Cluster: 集群协议

扩展协议 X-Upgrade: X-Cluster

集群应用示例

// 节点b1
XNet xNet = new XNet(":6001")
        .setAttr("cluster.master", ":5001") // master指向a
        .setAttr("cluster.name", "b") // 节点名(必须)
        .start();
// 节点b2
XNet xNet = new XNet(":6002")
        .setAttr("cluster.master", ":5001") // master指向a
        .setAttr("cluster.name", "b") // 节点名(必须)
        .start();
// 节点a1
XNet xNet = new XNet(":5001")
        .setAttr("cluster.name", "a") // 节点名(必须)
        .start();

Threaad.sleep(5 * 1000);
xnet.cluster().http("b", "/user/1").get(); // 会随机选择b的一个节点请求

集群配置

cluster.name: 节点名(必须)

  • 同名多实例节点自动组成集群

cluster.master: 集群master

  • 配置后节点会自动与master所持有的应用组成集群
    • 不定时向master上传自己的信息, 并获取集群中其它暴露给自己的节点信息
  • 支持格式例子(多个以逗号分割 :6000,:7000)
    • :6000
    • localhost:6000
    • https://:6000

cluster.exposeTo: 暴露给哪些应用

  • 应用与应用之间互通和隔离配置

  • 支持的格式(多个以逗号分割)

    • * : 表示匹配任意节点名
    • a1 : 匹配 a1
    • *a1: 匹配以 a1结尾的节点名
    • a1*: 匹配以 a1开头的节点名
  • 默认 * 暴露给所有节点

  • 本地开发环境可以配个不存在的应用名(比如 - ), 这样就可以让应用既获取集群其他应用节点, 又隔离于其他应用节点

cluster.proxyHp: 由额外的ip端口代理到本节点

  • 一般用于由nginx加域名隐藏后边的节点, 让集群中其他节点通过proxyHp访问到本节点

cluster.syncToMe: 要求master是否主动同步我(默认true)

  • 其他节点每次有更新都立即通知我
  • 会主动调用来请求节点的接口节点更新

cluster.backFeed: 要求master是在我每次注册的时候同步所有节点给我(默认false)

集群功能接口

  • 公共请求头部:

    header名 是否必须 header说明
    X-Upgrade 固定值:X-Cluster
    Content-Type application/json 或 application/x-www-form-urlencoded
    X-Request-ID 请求id

服务注册

被请求的是请求者的master

  • 接口路由:/nodeUp

  • 请求方法:POST

  • 参数说明:

    参数名 是否必须 参数说明
    name 节点名
    id 节点id(保证同名节点下唯一id)
    hp 请求节点暴露的访问ip和端口
    例: 192.168.1.1:8080 或 xxx.com 或 https://xxx.com
    exposeTo 暴露给哪些节点名
    多个以逗号分割
    例子: a,b
    默认为*暴露给所有节点
    syncToMe 其他节点有更新是否主动同步我
    会主动调用来请求节点的接口节点更新
    backFeed 立即同步所有节点给我
    会主动调用来请求节点的接口节点更新
  • 返回示例:

    {
      "code": "00", 
      "id": "b:laHi69J3On:1", // 请求id(可用X-Request-ID的值替代)
      "msg": null,
      "data": null,
      "mark": null // 参数传什么就返回什么
    }

节点更新

如果syncToMe为true: master会主动通过此接口同步变化

  • 接口路由:/nodeUpdate

  • 请求方法:POST

  • 参数说明:

    参数名 是否必须 参数说明
    name 节点名
    id 同名节点下唯一id
    hp 节点暴露的访问ip和端口
    例: 192.168.1.1:8080 或 xxx.com 或 https://xxx.com
    exposeTo 暴露给哪些节点名
    多个以逗号分割
    例子: a,b
    默认为*暴露给所有节点
    syncToMe 有更新是否主动同步我
  • 返回示例:

    {
      "code": "00", 
      "id": "b:laHi69J3On:1", // 请求id(可用X-Request-ID的值替代)
      "msg": null,
      "data": null,
      "mark": null // 参数传什么就返回什么
    }

节点下线

  • 接口路由:/nodeDown/{infect}

  • 请求方法:POST

  • 参数说明:

    参数名 是否必须 参数说明
    infect true: 通知所有
    false: 只下线一个节点
    name 节点名
    id 节点唯一id. 不传则匹配所有name的节点
  • 返回示例:

    {
      "code": "00", 
      "id": "b:laHi69J3On:1", // 请求id(可用X-Request-ID的值替代)
      "msg": null,
      "data": null,
      "mark": null // 参数传什么就返回什么
    }

获取节点

  • 接口路由:/nodes/{appName}

  • 请求方法:GET

  • 参数说明:

    参数名 是否必须 参数说明
    appName 节点名
  • 返回示例:

    {
      "code": "00",
      "data": [
        {
          "_master": false,
          "_uptime": 1686462464267,
          "exposeTo": [
            "*"
          ],
          "hp": {
            "host": "192.168.1.9",
            "port": 6000,
            "secure": false
          },
          "id": "b1",
          "name": "b",
          "syncToMe": true
        },
        {
          "_master": false,
          "_uptime": 1686462467716,
          "exposeTo": [
            "*"
          ],
          "hp": {
            "host": "192.168.1.9",
            "port": 6001,
            "secure": false
          },
          "id": "b2",
          "name": "b",
          "syncToMe": true
        }
      ],
      "id": "HgFGXbqlvoTvOCOnj7XMu",
      "mark": null,
      "msg": null
    }

获取所有节点名

  • 接口路由:/apps
  • 请求方法:GET
  • 参数说明: 无
  • 返回示例:
    {
      "code": "00",
      "data": [
          "a",
          "b",
          "c"
      ],
      "id": "lrzu64KGHuXKGcKhJUfHp",
      "mark": null,
      "msg": null
    }

获取master信息

  • 接口路由:/master
  • 请求方法:GET
  • 参数说明: 无
  • 返回示例:
    {
      "code": "00",
      "data": {
        "a": [
          {
            "_master": true,
            "_uptime": 1686462823298,
            "exposeTo": [
              "*"
            ],
            "hp": {
              "host": "192.168.1.9",
              "port": 5000,
              "secure": false
            },
          "id": "RgWPXGaqW8fLfDRLDmOUY",
          "name": "a",
          "syncToMe": true
          }
        ]
      },
      "id": "aDy5cvl9NhtfU64XCEB5X",
      "mark": null,
      "msg": null
    }

获取当前节点信息

  • 接口路由:/me
  • 请求方法:GET
  • 参数说明: 无
  • 返回示例:
    {
      "code": "00",
      "data": {
        "_master": false,
        "_uptime": 1686791259583,
        "exposeTo": [
          "*"
        ],
        "hp": {
          "host": "172.17.0.1",
          "port": 5000,
          "secure": false
        },
        "id": "UzTaQHCIbpW940nCgAjza",
        "name": "a",
        "syncToMe": true
      },
      "id": "hDMznYyPiyzNZTts3I57o",
      "mark": null,
      "msg": null
    }

X-ap: 同名节点数据同步

扩展协议 X-Upgrade: X-ap

一般用于同名多节点有内存缓存,缓存更改后和其他节点之间的数据同步通知

变更监听器

@Route(path = "user", protocol = AP.DATA_VERSION)
void ap_user(String dataKey, Long version) {
    // 处理同名应用其他节点的用户数据更改通知
}

变更通知

ap.update("user", "user1", System.currentTimeMillis());

X-PieceFile: 文件分片上传

扩展协议 X-Upgrade: X-PieceFile

  • http header
    • x-pieceupload-id: 上传id(必须)
    • x-pieceupload-length: 文件大小(第一次必须)
    • x-pieceupload-filename: 文件名(第一次可选)

前端代码示例

// 分片上传文件函数
function pieceUpload(file) {
    const uploading = { // 分片上传对象
        file: file,
        pause: false, // 是否暂停
        pieceSize: 1024 * 1024 * 5, // 每个分片的大小
        pos: 0, // 当前切片的位置
        progress: 0, // 上传的进度 0~100
        url: null, // 上传完成后的完整下载地址
        error: '',
        uploadId: (((1+Math.random())*0x10000)|0).toString(16) + (((1+Math.random())*0x10000)|0).toString(16) + '_' + new Date().getTime()
    };
    doUpload(uploading)
}

// 分片上传执行函数
function doUpload(uploading) {
  const fd = new FormData();
  const endIndex = Math.min(uploading.pos + uploading.pieceSize, uploading.file.size);
  // 分割当前上传的数据段
  fd.append('file', uploading.file.slice(uploading.pos, endIndex));
  // 配置http header
  const headers = {
    "Content-Type": "multipart/form-data",
    "X-Upgrade": "X-PieceFile",
    "x-pieceupload-id": uploading.uploadId,
  }
  if (uploading.pos === 0) { // 第一片必传参数
    headers['x-pieceupload-filename'] = uploading.file.name
    headers['x-pieceupload-length'] = uploading.file.size
  }

  // axios 执行上传动作
  axios.post('test/upload', fd, {type: 'post', headers,}).then(resp => {
    if (resp.data.code === '00') {
      uploading.pos += uploading.pieceSize
      // 判断所有分片是否已经上传完
      if (uploading.pos >= uploading.file.size) {
        uploading.progress = 100;
        uploading.url = '//' + window.location.host + '/file/' +resp.data.data.fileId
      }
      // 判断是否暂停
      else if (!uploading.pause) {
        uploading.progress = Math.floor((uploading.pos / uploading.file.size) * 100);
        const wait = resp.data.data.leftRead % uploading.pieceSize
        if (wait) { // 服务器处理慢,稍等上传
          setTimeout(() => doUpload(uploading), wait * 200)
        } else {
          doUpload(uploading)
        }
      }
    } else {
      // 上传错误处理
      uploading.error = resp.data.msg;
    }
  })
}

// 获取上传的文件
const fd = new FormData(document.getElementById("form"));
const file = fd.get('file');
pieceUpload(file)

分片上传返回结构

{
  "uploadId": "上传id",
  "fileId": "服务生成的文件id",
  "end": false, // 是否处理结束
  "leftRead": 1024 // 后端在已有的数据还剩多少没读取处理
}

后端最终文件接收示例

@Route(path = "upload", method = "post", protocol = PieceFileHandler.X_PIECE_FILE)
void upload(FileData file) throws Exception {
    if (file == null) return ApiResp.fail("文件未上传");
    File uploadDir = new File("./upload");
    uploadDir.mkdirs();
    file.transferTo(uploadDir);
    log.info("upload file: " + file);
}

X-cp: 类Zookeeper,满足分布式CP

TODO

X-mq: 消息队列

TODO

X-mapreduce: 分布式计算

TODO

X-s3: s3对象存储

TODO

GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

简介

以http为基础协议的多协议框架 展开 收起
Java 等 3 种语言
LGPL-3.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
Java
1
https://gitee.com/xnat/xnet.git
git@gitee.com:xnat/xnet.git
xnat
xnet
xnet
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891