服务器rad查看_无服务器计算:Rad Word聊天过滤器

服务器rad查看

云计算:梦想与现实 ( Cloud Computing: Dream vs Reality )

The dream of cloud computing is wonderful: you never run your own server, pay for electricity, or worry about network failures. Sadly, the reality is something else all together. You still have to administer the software on servers. You still need to design failover systems. You still have to secure the servers, even if they are virtual. Cloud computing requires you to build your own distributed computing infrastructure, you just don’t have to mess with the actual hardware anymore. It’s a nice dream, but cloud computing providers only deliver half of it.

云计算的梦想是美好的:您永远不会运行自己的服务器,支付电费或担心网络故障。 可悲的是, 现实是其他所有东西。 您仍然必须在服务器上管理软件。 您仍然需要设计故障转移系统。 即使服务器是虚拟的,您仍然必须保护服务器的安全。 云计算要求您构建自己的分布式计算基础架构,而不必再与实际的硬件搞混了。 这是一个不错的梦想,但是云计算提供商只能实现其中的一半。

The real dream is that you write some code that lives in the network. A message comes in and your code processes it, sending the messages back out. If you need to store some data you can just store it. If you need to call an external webservice you can call it. You don’t have worry about the file system or database administration. You don’t have to worry about whether to spin up 5 or 500 instances of your service. You don’t have worry about co-locating your services near where the users are. In short your code becomes truly serverless.

真正的梦想是编写一些驻留在网络中的代码。 出现一条消息,您的代码对其进行处理,然后将消息发回。 如果您需要存储一些数据,则可以将其存储。 如果您需要调用外部Web服务,则可以调用它。 您不必担心文件系统或数据库管理。 您不必担心是否要启动5或500个服务实例。 您不必担心将服务放置在用户所在的位置附近。 简而言之,您的代码真正变成了无服务器。

分布式服务器使简单代码变得困难 ( Distributed Servers Make Simple Code Hard )

Let’s consider a simple example. Suppose you want to build a chat app for junior high students with a profanity filter. This is conceptually very simple. It’s just an if statement. If the message contains any of a list of words, send it back to the student. In practice, however, this code is much harder to build.

让我们考虑一个简单的例子。 假设您要使用亵渎过滤器为初中学生构建聊天应用程序。 从概念上讲这很简单。 这只是一个if语句。 如果消息中包含任何单词列表,请将其发送回学生。 但是,实际上,此代码很难构建。

Making a simple text filter like this is difficult to scale; it requires sending the message from the end user, to the data stream network, back to your server, performing the computation, then back again to the network before reaching the final destination. This 'back and forth' adds latency and load to your server, for what is conceptually a simple if statement. And we haven’t even considered data storage and synchronization yet. Your server doesn’t even really want the messages, but it’s the only way to perform computation on data in motion.

像这样制作一个简单的文本过滤器很难扩展。 它需要将最终用户的消息发送到数据流网络,再发送回服务器,执行计算,然后发送回网络,然后到达最终目的地。 这种“来回”增加了服务器的延迟和负载,这在概念上是简单的if语句。 而且我们甚至还没有考虑数据存储和同步。 您的服务器甚至根本不需要消息,但这是对运动中的数据执行计算的唯一方法。

将计算移至数据 ( Move the Computation to the Data )

What if there was a better way? Instead of moving the data to the computation, what if you could move the computation to the data?

如果有更好的方法怎么办? 除了将数据移至计算之外,如果可以将计算移至数据怎么办?

PubNub has always had a Data Stream Network (DSN). It’s like a CDN, but for data in motion. Up until now the DSN could route that data in motion quickly and reliably, but not actually change the data in any way. That means you can’t edit contents or perform any computation. If you want to mutate a message you’d have to take it out of the DSN to your own server, do the modifications, then send back to PubNub before it reaches the end user.

PubNub一直都有一个数据流网络(DSN) 。 它就像CDN,但用于移动数据。 到目前为止,DSN可以快速可靠地路由移动中的数据,但实际上不以任何方式更改数据。 这意味着您无法编辑内容或执行任何计算。 如果您想要对邮件进行变异,则必须将其从DSN中删除到您自己的服务器上,进行修改,然后在到达最终用户之前将其发送回PubNub。

This roundabout method of realtime computing not only adds tremendous latency, but it also introduces a new single point of failure and completely destroys user locality. No matter where the data comes from, it has to go to a single server in a single location. If that server goes down, or is simply far away from the user, then the user experience massively suffers.

这种实时计算的回旋方法不仅增加了巨大的延迟,而且还引入了新的单点故障,并完全破坏了用户位置。 无论数据来自何处,都必须将其发送到单个位置的单个服务器。 如果该服务器出现故障,或者只是离用户很远,那么用户体验将遭受巨大损失。

Now there is a better way: PubNub BLOCKS. You really can write a simple text filter and send it into the network to be run. The code is put near the data it needs to operate on. When a message comes in the code is executed. No discrete servers. No downtime. Just simple logic running at scale. We like to say: BLOCKS just works.

现在有一个更好的方法:PubNub BLOCKS。 您确实可以编写一个简单的文本过滤器,并将其发送到网络中以运行。 该代码放在需要操作的数据附近。 出现消息时,将执行代码。 没有离散服务器。 无停机时间。 只是大规模运行的简单逻辑。 我们喜欢说:块就可以了。

But enough about the architecture. Let’s write some code!

但是关于架构就足够了。 让我们写一些代码!

建立您的第一个PubNub BLOCK ( Building your first PubNub BLOCK )

Getting started is easy. Just log into your free PubNub account.

入门很容易。 只需登录您的免费PubNub帐户即可。

Create PubNub Account

Create a new app with a pre-generated keyset.

使用预先生成的键集创建一个新应用。

Create New App

Now enable BLOCKS from the ‘application add-ons’ section.

现在,从“应用程序加载项”部分启用BLOCKS。

Enable BLOCKS

Next go to the BLOCKS screen and create a new block.

接下来转到“块”屏幕并创建一个新块。

Create New Block

Now add an event handler to filter the rad words. The type is set to Before Publish or Fire so that we can filter messages before they are sent to other users.

现在添加一个事件处理程序来过滤rad字。 该类型设置为“ Before Publish or Fire以便我们可以在邮件发送给其他用户之前对其进行过滤。

Create Event Handler

The code in your block is simple promise-based JavaScript. Below is a simple chat filter that looks for bad words, except we will look for ‘rad’ words. We don’t want the next generation becoming too radical. ‘Excellent’ and ‘Cool’ are fine, and even an occasional ‘awesome’, but ‘gnarly’, ‘tubluar’, and ‘grody’ are right out.

您块中的代码是简单的基于PromiseJavaScript。 下面是一个简单的聊天过滤器,用于查找不良单词,但我们将查找“ rad”单词。 我们不希望下一代变得过于激进。 “优秀”和“酷”很好,甚至偶尔有“很棒”,但“讨厌”,“笨拙”和“肮脏”都可以。

export default (request) => { 
    var radwords = ['gnarly','tubular','grody'];
    // fill in the final code
    for(var i=0; i < radwords.length; i++) {
      var rad = radwords[i];
        if (request.message.text.indexOf(rad) >= 0) {
            request.message.rejected = true;
            request.message.reason = 'the word ' + rad + ' is too radical!';
            console.log("request rejected", request.message);
            return request.ok();
        }
    }    

    return request.ok(); // Return a promise when you're done 
}

In a real application you’d want to delegate this filter to a 3rd party text analysis API, but for detecting radical speech this will work well enough. Now save and start your BLOCK by pressing the Save button and the ‘Start Block’ button.

在实际的应用程序中,您希望将此过滤器委派给第三方文本分析API,但是对于检测激进的语音,此方法已经足够好了。 现在,按“保存”按钮和“启动块”按钮,保存并启动BLOCK。

Test the block out by putting in this test message, then watch the console.

通过输入此测试消息来测试该块,然后查看控制台。

{
    "text": "BLOCKS are tubular"
}

Filter Block in Action

It’s really that easy. You’ve built a filter that can scale to millions of annoying middle school students.

真的很容易。 您已经建立了一个过滤器,可以扩展到数百万恼人的中学生。

Of course this won’t be very useful without an actual chat app to go with it. PubNub makes that easy too.

当然,如果没有一个实际的聊天应用程序,这将不是很有用。 PubNub也很容易实现。

构建一个HTML聊天应用程序 ( Build an HTML Chat App )

PubNub’s JavaScript API is very easy to use and can be embedded in any webpage (or NodeJS app, or ReactNative app, etc). Let’s start with a simple webpage:

PubNub的JavaScript API非常易于使用,可以嵌入任何网页(或NodeJS应用程序或ReactNative应用程序等)中。 让我们从一个简单的网页开始:

<html>
<head>
  <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.0.8.js"></script>
  <style type="text/css">
      .hbox {
        display: -webkit-flex;
        display: flex;
        -webkit-flex-direction: row;
        flex-direction: row;
        width: 50em;
      }
      .grow {  flex: 1;   }
      textarea { height: 30em; }
      #error { color: red; }
  </style>
<body>
  <div class='hbox'>
    <textarea id='history' class='grow'></textarea>
  </div>
  <div class='hbox'>
    <input id='message' class='grow'/>
    <button id='send'>Send</button>
  </div>
  <div class='hbox' id='error'></div>
<script type="text/javascript">
</script>
</body>
</html>

The HTML above creates a simple chat view. There is a textarea for the history above an input field and a send button. I’m using Flexbox[link] (now supported everywhere) to create hbox and grow classes which let us nicely align the different views. Notice the hbox with an id of error doesn’t have any content. We’ll dynamically add this in a moment

上面HTML创建了一个简单的聊天视图。 在输入字段和发送按钮上方有一个用于历史记录的文本区域。 我正在使用Flexbox [link](现在到处都受支持)来创建hboxgrow类,这使我们可以很好地对齐不同的视图。 请注意,带有error ID的hbox没有任何内容。 我们稍后会动态添加

It looks like this:

看起来像这样:

Chat Interface

Now we can connect to the network. From your PubNub admin dashboard, get your subscribe and publish keys. It is these keys which let your code access PubNub’s network.

现在我们可以连接到网络了。 在您的PubNub管理控制台中,获取您的订阅和发布密钥。 这些密钥使您的代码可以访问PubNub的网络。

In the script element, add this code:

script元素中,添加以下代码:

// a simple JQuery like function to get elements by ID
function $(id) {
  return document.getElementById(id);
}

//configure pubnub
var pubnub = new PubNub({
    subscribeKey:"sub-c-f065409c-76af-11e6-86e5-02ee2ddab7fe",
    publishKey:"pub-c-2da9d382-65a4-4592-9804-aa2f2b28e12d"
});

Calling new PubNub() sets up a connection to the data stream network with your access keys. The JavaScript API has many parameters you can tweak, but the defaults generally suffice. Next add a listener

调用new PubNub()可以使用访问密钥建立到数据流网络的连接。 JavaScript API有许多您可以调整的参数,但是默认值通常就足够了。 接下来添加一个监听器

//when message comes in
pubnub.addListener({
  message: function(msg) {
    //if rejected, show error
    if(msg.message.rejected) {
      $('error').innerHTML = msg.message.reason;
      return;
    }
    //append to history
    $('history').value += msg.message.text + '\n';
  }
});

Every time a message comes in this listener will be called. It will check if the message was rejected. If it was then it sents the error message and returns. If the message was not rejected it appends it to the history.

每次有消息传入时,都会调用此侦听器。 它将检查邮件是否被拒绝。 如果是,则发送错误消息并返回。 如果邮件未被拒绝,则将其附加到历史记录中。

//listen to the 'radchat' channel
pubnub.subscribe({channels:['radchat']});

This code subscribes to the channel called radchat. This is the same channel our block is using. You can have as many channels as you want, but a block can only operate on one channel at a time.

这段代码订阅了名为radchat的频道。 这是我们的块使用的相同通道。 您可以根据需要拥有任意数量的通道,但是一个块一次只能在一个通道上运行。

//which click the send button
$('send').addEventListener('click',function() {
    //send the message
    pubnub.publish({
      channel:'radchat',
      message:{text: $('message').value}
    });
    $('error').innerHTML = '';
});

This sends a new message to the radchat channel every time the user presses the send button. Now check that the block is still running and try sending a message. That’s it! You’ve just made a massively scalable chat app with rad word filtering.

每次用户按下发送按钮时,都会向radchat频道发送一条新消息。 现在,检查该块是否仍在运行,然后尝试发送消息。 而已! 您刚刚制作了具有rad单词过滤功能的可大规模扩展的聊天应用程序。

Chat App in Action

这个怎么运作 ( How it works )

When you write a block it is running in live in the Data Stream Network. You can send messages to the block through the dashboard or from your own client side code. When you press the start button the code for your block is instantly sent to every part of the PubNub network around the globe. Now any messages sent to your channel will be handled by an instance of your block running in the data center nearest to the message.

当您编写一个块时,它正在数据流网络中实时运行。 您可以通过仪表板或您自己的客户端代码将消息发送到块。 当您按下开始按钮时,您的代码块将立即发送到全球PubNub网络的每个部分。 现在,发送到您的频道的所有消息将由最靠近消息的数据中心中运行的块实例处理。

When you update the code for your block, the update is applied to the entire network at once. There is no down time between the old block and the new one. No messages will ever be dropped. Every message will be handled by your code.

当您更新块的代码时,更新将立即应用于整个网络。 在旧块和新块之间没有停机时间。 没有消息将被丢弃。 每条消息将由您的代码处理。

For maximum safety and reliability, PubNub BLOCKS uses multiple levels of security. Each block is run inside of a NodeJS virtual machine with access to a very restricted set of APIs. Block code can never access the filesystem or host operating system. Next the entire Node instance is run using cgroups to isolate each process from the others and the host operating system. The use of cgroups ensures a badly written or malicious block can’t consume all resources on the physical machine or access data from another developer’s block. It also provides extra hooks for monitoring and management.

为了获得最大的安全性和可靠性,PubNub BLOCKS使用了多个安全级别。 每个块都在NodeJS虚拟机内部运行,可以访问一组非常受限的API。 块代码永远无法访问文件系统或主机操作系统。 接下来,使用cgroup运行整个Node实例,以将每个进程与其他进程和主机操作系统隔离开。 使用cgroup可以确保写得不好的块或恶意的块不会消耗物理机上的所有资源,也不会访问其他开发者块的数据。 它还为监视和管理提供了额外的挂钩。

BLOCKS is built on top of the existing secure Data Stream Network so all communication with the outside world is secure and sensitive payloads can be further encrypted on the end device for extra end-to-end security. The Access Manager APIs provide additional access control at the channel level, to further protect sensitive data streams.

BLOCKS建立在现有安全数据流网络之上,因此与外界的所有通信都是安全的,敏感的有效负载可以在终端设备上进一步加密,以提供额外的端到端安全性。 Access Manager API在通道级别提供其他访问控制,以进一步保护敏感数据流。

For storage, BLOCKS provides a built in key value store called KV Store. You can store and retrieve chat messages or any other JSON-like object in the datastore using the Promise based API. The datastore provides an eventually consistent data model so computation can continue without waiting for locks or synchronization.

对于存储,BLOCKS提供了一个内置的键值存储,称为KV Store 。 您可以使用基于Promise的API在数据存储区中存储和检索聊天消息或任何其他类似JSON的对象。 数据存储区提供了最终一致的数据模型,因此计算可以继续进行而无需等待锁定或同步。

One of BLOCKS overarching goals is to maintain low-latency response to realtime messages. We do this by moving computation to where the data is instead of the other way around. The code for your block is sent to multiple edge nodes around the globe simultaneously then messages are routed to the closest edge node.

BLOCKS的首要目标之一是保持对实时消息的低延迟响应。 我们通过将计算移动到数据所在的位置来实现此目的,而不是相反。 您块的代码同时发送到全球各地的多个边缘节点,然后将消息路由到最近的边缘节点。

Additionally, alll APIs are designed to minimize latency through the use of promises and lack of data locking. If your code needs to invoke an external webservice that might take a while to respond, the event handler can both wait for the webservice callback and also send a message to the end user immediately. The immediate message gives the user the information they need right now. When the callback completes your event handler can send an additional followup message with additional information.

此外,Alll API旨在通过使用Promise和缺少数据锁定来最大程度地减少延迟。 如果您的代码需要调用可能需要一段时间才能响应的外部Web服务,则事件处理程序既可以等待Web服务回调,也可以立即向最终用户发送消息。 立即消息为用户提供了他们现在所需的信息。 回调完成后,事件处理程序可以发送带有其他信息的其他后续消息。

微服务扩展 ( Scaling with Microservices )

Imagine you built a realtime voting app. 1000 students on a campus can vote on their favorite topic instantly, with a realtime vote tally. You could build this with a quick and dirty NodeJS server to calculate the totals and handle the messaging with websockets. It’s easy. Now imagine you want to scale it to next season’s audience for Dancing with the Stars. Ten million viewers at once. Oops. Not so easy.

假设您构建了一个实时投票应用程序。 校园中的1000名学生可以实时投票统计自己喜欢的话题。 您可以使用快速且肮脏的NodeJS服务器来构建它,以计算总数并使用websocket处理消息传递。 这很容易。 现在想象一下,您想将其扩展到下一季的“与星共舞”听众。 一次有1000万观众。 哎呀。 没那么容易。

Scaling computation is hard. Really hard. And annoying. The problem you want to solve is making a good looking voting app, not distributed synchronization and computation. PubNub BLOCKS makes the problem simple again. It removes the single point of failure of cloud computing. No patching and rebooting the operating system. No syncing. Get back to writing useful code, not wasting time on server headaches. Every second you have to spend on infrastructure is a second you can’t spend on making your application better.

缩放计算很难。 真的很难。 和烦人。 您要解决的问题是制作一个外观漂亮的投票应用程序,而不是分布式同步和计算。 PubNub BLOCKS使问题再次变得简单。 它消除了云计算的单点故障。 无需修补和重新引导操作系统。 没有同步。 回到编写有用的代码,而不是浪费时间在服务器上。 您必须花在基础架构上的每一秒钟都是您不能花费在改善应用程序上的每一秒钟。

So go get started now. What will you build?

所以现在就开始吧 。 你会建造什么?

翻译自: https://scotch.io/tutorials/serverless-computing-a-rad-word-chat-filter

服务器rad查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值