ballerina 学习二十一 http2

ballerina 支持http2 协议,包含server push

http2 协议

  • 参考代码
import ballerina/http;
import ballerina/log;endpoint http:Client http2serviceClientEP {
    url: "http://localhost:7090",
    httpVersion: "2.0"};@http:ServiceConfig {
    basePath: "/http11Service"
}
service<http:Service> http11Service bind { port: 9090 } { @http:ResourceConfig {
        path: "/"
    }
    http11Resource(endpoint caller, http:Request clientRequest) {
        var clientResponse =
            http2serviceClientEP->forward("/http2service", clientRequest); http:Response response = new;
        match clientResponse {
            http:Response resultantResponse => {
                response = resultantResponse;
            }
            error err => {
                response.statusCode = 500;
                response.setPayload(err.message); }
        }
        caller->respond(response) but {
            error e => log:printError(
                           "Error occurred while sending the response",
                           err = e) }; }
}endpoint http:Listener http2serviceEP {
    port: 7090,
    httpVersion: "2.0"};@http:ServiceConfig {
    basePath: "/http2service"
}
service http2service bind http2serviceEP { @http:ResourceConfig {
        path: "/"
    }
    http2Resource(endpoint caller, http:Request clientRequest) {
        http:Response response = new;
        json msg = { "response": { "message": "response from http2 service" } };
        response.setPayload(msg);
        caller->respond(response) but {
            error e => log:printError(
                           "Error occurred while sending the response",
                           err = e) }; }
}

server push

  • 参考代码
import ballerina/http;
import ballerina/log;
endpoint http:Listener http2ServiceEP {
    port: 7090,
    httpVersion: "2.0"};@http:ServiceConfig {
    basePath: "/http2Service"
}
service http2Service bind http2ServiceEP { @http:ResourceConfig {
        path: "/"
    }
    http2Resource(endpoint caller, http:Request req) {
        http:PushPromise promise1 = new(path = "/resource1", method = "GET");
        caller->promise(promise1) but {
            error e => log:printError(
                           "Error occurred while sending the promise1",
                           err = e) };
        http:PushPromise promise2 = new(path = "/resource2", method = "GET");
        caller->promise(promise2) but {
            error e => log:printError(
                           "Error occurred while sending the promise2",
                           err = e) };
        http:PushPromise promise3 = new(path = "/resource3", method = "GET");
        caller->promise(promise3) but {
            error e => log:printError(
                           "Error occurred while sending the promise3",
                           err = e) };
        http:Response response = new;
        json msg = { "response": { "name": "main resource" } };
        response.setPayload(msg);
        caller->respond(response) but {
            error e => log:printError(
                           "Error occurred while sending the response",
                           err = e) };
        http:Response push1 = new;
        msg = { "push": { "name": "resource1" } };
        push1.setPayload(msg);
        caller->pushPromisedResponse(promise1, push1) but {
            error e => log:printError(
                           "Error occurred while sending the promised response1",
                           err = e) };
        http:Response push2 = new;
        msg = { "push": { "name": "resource2" } };
        push2.setPayload(msg);
        caller->pushPromisedResponse(promise2, push2) but {
            error e => log:printError(
                           "Error occurred while sending the promised response2",
                           err = e) };
        http:Response push3 = new;
        msg = { "push": { "name": "resource3" } };
        push3.setPayload(msg);
        caller->pushPromisedResponse(promise3, push3) but {
            error e => log:printError(
                           "Error occurred while sending the promised response3",
                           err = e) }; }
}
import ballerina/http;
import ballerina/log;
endpoint http:Client clientEP {
    url: "http://localhost:7090",
    httpVersion: "2.0"};function main(string... args) { http:Request serviceReq = new;
    http:HttpFuture httpFuture = new;
    var submissionResult = clientEP->submit("GET", "/http2Service", serviceReq); match submissionResult {
        http:HttpFuture resultantFuture => {
            httpFuture = resultantFuture;
        }
        error resultantErr => {
            log:printError("Error occurred while submitting a request",
                            err = resultantErr);
            return;
        }
    }
 http:PushPromise[] promises = [];
    int promiseCount = 0;
    boolean hasPromise = clientEP->hasPromise(httpFuture); while (hasPromise) {
        http:PushPromise pushPromise = new;
        var nextPromiseResult = clientEP->getNextPromise(httpFuture); match nextPromiseResult {
            http:PushPromise resultantPushPromise => {
                pushPromise = resultantPushPromise;
            }
            error resultantErr => {
                log:printError("Error occurred while fetching a push promise",
                                err = resultantErr);
                return;
            }
        }
        log:printInfo("Received a promise for " + pushPromise.path); if (pushPromise.path == "/resource2") {
            clientEP->rejectPromise(pushPromise); log:printInfo("Push promise for resource2 rejected");
        } else {
            promises[promiseCount] = pushPromise; promiseCount = promiseCount + 1;
        }
        hasPromise = clientEP->hasPromise(httpFuture);
    } http:Response response = new;
    var result = clientEP->getResponse(httpFuture); match result {
        http:Response resultantResponse => {
            response = resultantResponse;
        }
        error resultantErr => {
            log:printError("Error occurred while fetching response",
                            err = resultantErr);
            return;
        }
    } var responsePayload = response.getJsonPayload();
    match responsePayload {
        json resultantJsonPayload =>
              log:printInfo("Response : " + resultantJsonPayload.toString());
        error e =>
              log:printError("Expected response payload not received", err = e);
    }
    foreach promise in promises {
        http:Response promisedResponse = new;
        var promisedResponseResult = clientEP->getPromisedResponse(promise);
        match promisedResponseResult {
            http:Response resultantPromisedResponse => {
                promisedResponse = resultantPromisedResponse;
            }
            error resultantErr => {
                log:printError("Error occurred while fetching promised response",
                                err = resultantErr);
                return;
            }
        }
        var promisedPayload = promisedResponse.getJsonPayload();
        match promisedPayload {
            json promisedJsonPayload =>
                       log:printInfo("Promised resource : " +
                                      promisedJsonPayload.toString());
            error e =>
                  log:printError("Expected promised response payload not received",
                                  err = e);
        }
    }}

参考资料

https://ballerina.io/learn/by-example/http-2.0-server-push.html
https://ballerina.io/learn/by-example/http-1.1-to-2.0-protocol-switch.html

原文地址:https://www.cnblogs.com/rongfengliang/p/9123699.html

时间: 2024-07-31 07:19:33

ballerina 学习二十一 http2的相关文章

java核心学习(二十一) 多线程---创建启动线程的三种方式

本节开始java多线程编程的学习,对于操作系统.进程.线程的基本概念不再赘述,只是了解java对于多线程编程的支持有哪些. 一.继承Thread类来创建线程 java语言中使用Thread类来代表线程,代表线程的类可以通过继承Thread类并重写run()方法来实现多线程开发,调用线程类实例的start方法来启动该线程.下面来试一试 package ThreadTest; public class FirstThread extends Thread{ private int i; public

ballerina 学习二十三 扩展ballerina

扩展ballerina 目前有三种方式: 扩展client connector的包 (数据库访问,基础设施,api) 扩展server listenner 绑定为不同的协议 添加新的注解到ballerina 源码进行编译并修改运行软件包 创建client connector client connector 由开发人员在创建endpoint 时进行初始化,你自己可以开发自己的connector 并发布到私服,或者照中央仓库 创建 client connector 的步骤 参考例子 https:/

ballerina 学习二十五 项目docker 部署&amp;&amp; 运行

ballerina 官方提供了docker 的runtime,还是比较方便的 基本项目创建 使用cli创建项目 按照提示操作就行 ballerina init -i 项目结构 添加了dockerfile 以及docker-compose 简单http 服务 ├── Ballerina.toml ├── Dockerfile ├── README.md ├── docker-compose.yml ├── hello_service.bal ├── target │ └── hello_servi

android学习二十一(使用Pull解析xml)

使用Pull解析xml 为了测试从网上得到的数据信息,我们需要配置一台服务器,我使用的是tomcat6.0,怎么配置tomcat我就不讲解了.配置好了以后在apache-tomcat-6.0.39\webapps\ROOT路径下面放置一个文件就可以通过浏览器来访问了 ,比如:放置了 一个hello.html文件,浏览器进行访问的路径是:http://localhost:8080/hello.html 现在在root目录下新建一个get_data.xml文件,内容如下: <apps> <a

Java学习(二十一):Properties配置文件的读取

Properties类继承自Hashtable它提供了几个主要的方法:1. getProperty ( String key),用指定的键在此属性列表中搜索属性.也就是通过参数key ,得到key所对应的value.2. load ( InputStream inStream),从输入流中读取属性列表(键和元素对).通过对指定的文件进行装载来获取该文件中的所有键-值对.以供 getProperty ( String key) 来搜索.3. setProperty ( String key, St

学习二十一

五周第三次课(3月7日)8.1 shell介绍8.2 命令历史8.3 命令补全和别名8.4 通配符8.5 输入输出重定向Linux Shell基础yum list |grep zsh 命令查询有没有安装该命令命令历史系统内置的变量决定了 系统会存储多少条运行的命令echo $HISTSIZE-c 清空内存中运行过的命令历史,但是不会清空配置文件cat .bash_history 查看操作记录历史,但是会在你退出终端的时候存储进去echo $HISTSIZE 查看当前历史能存多少命令如何更改变量,

Android学习路线(二十一)运用Fragment构建动态UI——创建一个Fragment

你可以把fragment看成是activity的模块化部分,它拥有自己的生命周期,接受它自己的输入事件,你可以在activity运行时添加或者删除它(有点像是一个"子activity",你可以在不同的activity中重用它).本课将向你展示如何使用Support Libaray继承 Fragment 类来让你的应用能够兼容正在运行Android 1.6的设备. 提示: 如果你决定你的应用需求的最低API级别是11或者更高,那么你不需要使用Support Library,你可以直接使用

马哥学习笔记二十一——LVS DR模型

kernel parameter: arp_ignore: 定义接收到ARP请求时的响应级别: 0:只要本地配置的有相应地址,就给予响应: 1:仅在请求的目标地址配置请求到达的接口上的时候,才给予响应: arp_announce:定义将自己地址向外通告时的通告级别: 0:将本地任何接口上的任何地址向外通告: 1:试图仅向目标网络通告与其网络匹配的地址: 2:仅向与本地接口上地址匹配的网络进行通告: curl命令选项: --cacert <file> CA证书 (SSL) --capath &l

Swift 学习之二十一:?和 !(详解)

Swift语言使用var定义变量,但和别的语言不同,Swift里不会自动给变量赋初始值, 也就是说变量不会有默认值,所以要求使用变量之前必须要对其初始化 .如果在使用变量之前不进行初始化就会报错: [plain] view plaincopyprint? var stringValue : String //error: variable 'stringValue' used before being initialized //let hashValue = stringValue.hashV