hi,你好!欢迎访问本站!登录
本站由简数采集腾讯云宝塔系统阿里云强势驱动
当前位置:首页 - 教程 - 杂谈 - 正文 君子好学,自强不息!

微软的分布式运用框架 Dapr Helloworld

2019-11-18杂谈搜奇网68°c
A+ A-

Dapr HelloWorld

Dapr

Distributed Application Runtime. An event-driven, portable runtime for building microservices on cloud and edge.

分布式运用运转时、事宜驱动、为云和边沿构建微效劳供应便携化运转时。

我如今也不是很懂。

dapr/dapr

GitHub

Dapr is a portable, serverless, event-driven runtime that makes it easy for developers to build resilient, stateless and stateful microservices that run on the cloud and edge and embraces the diversity of languages and developer frameworks.

Dapr codifies the best practices for building microservice applications into open, independent, building blocks that enable you to build portable applications with the language and framework of your choice. Each building block is independent and you can use one, some, or all of them in your application.

比上面的引见多了 stateless or stateful 的标签。学《盘算理论》的时刻打仗过一些状况机。

”状况是万恶之源“ 

注重提到了多言语和多开辟者框架,我以为这是他挑选的经由历程通讯同享信息,即 HTTPGRPC 支撑多言语等特征。微软想经由历程这个设定一个构建微效劳运用的划定规矩。从根本上建立你开辟的每个运用的独立性。

下面举行一个 QuickStart

环境

  1. Install Docker(微效劳已离不开容器化了)
  2. Install Dapr
  3. Node.js version 8 or greater(这个 Helloworld 是 node 运用)

On MacOS

Install the latest darwin Dapr CLI to /usr/local/bin

curl -fsSL https://raw.githubusercontent.com/dapr/cli/master/install/install.sh | /bin/bash

有条件可以加快

实行初始化(会启动 docker 容器)

$ dapr init
⌛  Making the jump to hyperspace...
Downloading binaries and setting up components
✅  Success! Dapr is up and running

$ docker ps
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                        NAMES
b3a5600e672f        redis                "docker-entrypoint.s…"   44 hours ago        Up 44 hours         0.0.0.0:6379->6379/tcp       xenodochial_hofstadter
e5010ba0c33f        daprio/dapr          "./placement"            44 hours ago        Up 44 hours         0.0.0.0:50005->50005/tcp     dapr_placement

HelloWorld

Application Architecture


可以看到暴露两个 endpoint 是 HTTP 接见,一个建立一个查询。

重要看我们运用 Dapr 的交互。在图中它作为 Runtime 

  • 供应 Dapr API 给多言语挪用。
  • 供应 状况治理 By state stores

Download Code

下载并进入响应文件夹

git clone https://github.com/dapr/samples.git
cd samples/1.hello-world

Cat app.js

// $ cat app.js 
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
// ------------------------------------------------------------

const express = require('express');
const bodyParser = require('body-parser');
require('isomorphic-fetch');

const app = express();
app.use(bodyParser.json());

const daprPort = process.env.DAPR_HTTP_PORT || 3500;
const stateUrl = `http://localhost:${daprPort}/v1.0/state`;
const port = 3000;

app.get('/order', (_req, res) => {
    fetch(`${stateUrl}/order`)
        .then((response) => {
            return response.json();
        }).then((orders) => {
            res.send(orders);
        });
});

app.post('/neworder', (req, res) => {
    const data = req.body.data;
    const orderId = data.orderId;
    console.log("Got a new order! Order ID: " + orderId);

    const state = [{
        key: "order",
        value: data
    }];

    fetch(stateUrl, {
        method: "POST",
        body: JSON.stringify(state),
        headers: {
            "Content-Type": "application/json"
        }
    }).then((response) => {
        console.log((response.ok) ? "Successfully persisted state" : "Failed to persist state");
    });

    res.status(200).send();
});

app.listen(port, () => console.log(`Node App listening on port ${port}!`));

这是一些路由和 handlers

注重 14-16 行

const daprPort = process.env.DAPR_HTTP_PORT || 3500;
const stateUrl = `http://localhost:${daprPort}/v1.0/state`;
const port = 3000;

3500 是 Dapr 的环境端口,假如你装置时有修改,须要斟酌。
stateurl 就是 Dapr 供应的 URL 了

Handlers

/neworder
app.post('/neworder', (req, res) => {
    const data = req.body.data;
    const orderId = data.orderId;
    console.log("Got a new order! Order ID: " + orderId);

    const state = [{
        key: "order",
        value: data
    }];

    fetch(stateUrl, {
        method: "POST",
        body: JSON.stringify(state),
        headers: {
            "Content-Type": "application/json"
        }
    }).then((response) => {
        console.log((response.ok) ? "Successfully persisted state" : "Failed to persist state");
    });

    res.status(200).send();
});

这里重点是状况存储,行将 state 经由历程 stateurl 存储在 Dapr 中。

/order

我们并非直接经由历程 res.json 作为 Response 来举行已耐久化的数据的运用,而是经由历程暴露一个 GET endpoint 经由历程接见它来考证耐久化是不是胜利。

app.get('/order', (_req, res) => {
    fetch(`${stateUrl}/order`)
        .then((response) => {
            return response.json();
        }).then((orders) => {
            res.send(orders);
        });
});

如今我们经由历程状况转移在 Dapr 里完成了 stateless,一样我们也可以在加上一个 local cache 并经由历程一个新的 endpoint 接见来使 Node application 变成 stateful

Dapr Run Node.js App

  1. npm install :经由历程当前目录下的 package.json , 会装置 express 和 body-parser ,在 app.js 7-8行我们可以看到这两项。
  2. dapr run --app-id mynode --app-port 3000 --port 3500 node app.js
$ dapr run --app-id mynode --app-port 3000 --port 3500 node app.js
ℹ️  Starting Dapr with id mynode. HTTP Port: 3500. gRPC Port: 55099
✅  You're up and running! Both Dapr and your app logs will appear here.

应该是有背景运转的 CLI 敕令,这里是前台打印的日记

== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="starting Dapr Runtime -- version 0.1.0 -- commit 4358565-dirty"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="log level set to: info"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="standalone mode configured"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="dapr id: mynode"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="loaded component messagebus (pubsub.redis)"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="loaded component statestore (state.redis)"
== DAPR == time="2019-11-06T10:37:41+08:00" level=info msg="application protocol: http. waiting on port 3000"
== APP == Node App listening on port 3000!
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="application discovered on port 3000"
== DAPR == 2019/11/06 10:37:42 redis: connecting to localhost:6379
== DAPR == 2019/11/06 10:37:42 redis: connected to localhost:6379 (localAddr: [::1]:55130, remAddr: [::1]:6379)
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actor runtime started. actor idle timeout: 1h0m0s. actor scan interval: 30s"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: starting connection attempt to placement service at localhost:50005"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="http server is running on port 3500"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="gRPC server is running on port 55099"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="local service entry announced"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="dapr initialized. Status: Running. Init Elapsed 945.8297490000001ms"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: established connection to placement service at localhost:50005"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: placement order received: lock"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: placement order received: update"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: placement tables updated"
== DAPR == time="2019-11-06T10:37:42+08:00" level=info msg="actors: placement order received: unlock"

⚠️:注重到 Node App 在指定的 3000 端口运转,同时另有状况存储的 redis6379 端口运转

Post and Get

接下来注重,文中的端口是 app.js 里默许的 3500

Post

Curl
curl -XPOST -d @sample.json http://localhost:3500/v1.0/invoke/mynode/method/neworder

Vscode

假如你用 vscode ,运用这个插件 Rest Client Plugin
然后翻开目录下的 sample.http , 可以看到 send request 的选项
sample.http 

POST http://localhost:3500/v1.0/invoke/mynode/method/neworder
{
  "data": {
    "orderId": "42"
  } 
}

Postman

如图: http://localhost:3500/v1.0/invoke/mynode/method/neworder 

Result Update

你可以在你启动的终端中看到新的日记

== APP == Got a new order! Order ID: 42
== APP == Successfully persisted state

Get

Curl
curl http://localhost:3500/v1.0/invoke/mynode/method/order

Vscode

sample.http

GET http://localhost:3500/v1.0/invoke/mynode/method/order

Postman

Terminate

ctrl + c 或许 dapr stop --app-id mynode

^C
ℹ️  terminated signal received: shutting down
✅  Exited Dapr successfully
✅  Exited App successfully

Feature

  • 具有可插进去供应顺序和最少一次语义的事宜驱动的Pub-Sub体系
  • 运用可插进去供应顺序的输入和输出绑定
  • 具有可插拔数据存储的状况治理
  • 一致的效劳到效劳发明和挪用
  • 挑选到场状况模子:壮大/终究一致性,初次写入/末了写入得胜
  • 跨平台假造演员
  • 限速
  • 运用OpenTelemetry的内置分布式跟踪
  • 运用专用的Operator和CRD在Kubernetes上当地运转
  • 经由历程HTTP和gRPC支撑一切编程言语
  • 来自Azure,AWS,GCP的多云,开放式组件(绑定,宣布-定阅,状况)
  • 作为历程或容器化在任何地方运转
  • 轻量级(58MB二进制,4MB物理内存)
  • 作为辅助工具运转-无需特别的SDK或库
  • 专用的CLI-易于调试的开辟人员友爱体验
  • Java,Dotnet,Go,Javascript和Python的客户端

Refer

  • https://github.com/dapr/dapr
  • https://github.com/dapr/docs/blob/master/getting-started/environment-setup.md#environment-setup
  • https://github.com/dapr/docs/tree/master/howto
  • https://github.com/dapr/samples
  • https://github.com/dapr/samples/tree/master/1.hello-world
  选择打赏方式
微信赞助

打赏

QQ钱包

打赏

支付宝赞助

打赏

  移步手机端
微软的分布式运用框架 Dapr Helloworld

1、打开你手机的二维码扫描APP
2、扫描左则的二维码
3、点击扫描获得的网址
4、可以在手机端阅读此文章
未定义标签

本文来源:搜奇网

本文地址:https://www.sou7.cn/282407.html

关注我们:微信搜索“搜奇网”添加我为好友

版权声明: 本文仅代表作者个人观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。请记住本站网址https://www.sou7.cn/搜奇网。

发表评论

选填

必填

必填

选填

请拖动滑块解锁
>>