cloudflare_无服务器Cloudflare员工非常出色

cloudflare

Serverless is the new black. I mean everybody I know is moving to the serverless platforms or launching one. OK, maybe not everyone but Cloudflare is definitely moving in this direction with an audacious relatively new project called Workers.dev (check out that coolest new domain extension .dev Google just made available).

无服务器是新的黑手党。 我的意思是,我认识的每个人都在转向无服务器平台或启动一个平台。 是的,也许不是每个人都可以,但是Cloudflare肯定正在通过一个名为Workers.dev的相对大胆的相对较新的项目朝这个方向发展 (请查看Google刚刚提供了最酷的新域扩展.dev )。

Today, let's explore what the heck is this new serverless platform about, how is it different than other serverless platforms (did someone say no cold starts!), and what do you say, let's write our first Cloudflare Worker.

今天,让我们探索这个新的无服务器平台到底有什么用,它与其他无服务器平台有何不同(有人说没有冷门开始!),您怎么说,让我们写我们的第一个Cloudflare Worker。

什么是Cloudflare工作者? ( What Are Cloudflare Workers? )

Let's understand Cloudflare Workers deeply. What's the big catch here?

让我们深入了解Cloudflare Workers。 这里有什么大收获?

Cloudflare Workers provides a serverless execution environment that allows you to create entirely new applications or augment existing ones without configuring or maintaining infrastructure. — Cloudflare Docs

Cloudflare Workers提供了一个无服务器执行环境,使您无需配置或维护基础结构即可创建全新的应用程序或扩充现有的应用程序。 — Cloudflare文件

  • You get a serverless execution environment

    您将获得一个无服务器执行环境
  • You can create entire new serverless apps

    您可以创建全新的无服务器应用程序
  • What?! You can change the behavior of existing apps

    什么?! 您可以更改现有应用程序的行为
  • and do all that without configuring or maintaining infrastructure

    并且无需配置或维护基础架构即可完成所有这些操作

all this sounds pretty awesome, tell me more! — Happy to oblige.

this 所有这些听起来都很棒,告诉我更多 ! —很乐意。

cloudflare_无服务器Cloudflare员工非常出色_第1张图片

Serverless Computing with Cloudflare Workers. The Network is the Computer. Build serverless applications on Cloudflare's global cloud network of 165 data centers. — Cloudflare Workers

Cloudflare Workers的无服务器计算。 网络就是计算机。 在由165个数据中心组成的Cloudflare的全球云网络上构建无服务器应用程序。 — Cloudflare工人

  • 165 Data Centers: Cloudflare is known for having one of the biggest CDN networks in the world. Just to put things in perspective here, Cloudflare’s network capacity is 15x bigger than the largest DDoS attack ever recorded. It has a 25 Tbps of capacity, it can handle any modern distributed attack.

    165个数据中心 :Cloudflare以拥有世界上最大的CDN网络之一而闻名。 只是为了说明问题,Cloudflare的网络容量比有记录的最大DDoS攻击大15倍。 它具有25 Tbps的容量,可以处理任何现代分布式攻击。
  • Dirt Cheap: The entire network of data centers can be used for your serverless apps. Which is amazing for scaling your next awesome API side project. It's dirt cheap. $5 per month for 10 million requests and then $0.5 per million requests. Folks like Troy Hunt are using Cloudflare Workers to identify pwned passwords.

    价格便宜 :整个数据中心网络均可用于您的无服务器应用程序。 对于扩展您的下一个很棒的API辅助项目而言,这是惊人的。 真便宜。 每月$ 5(适用于1000万个请求) ,然后为$ 0.5(每百万个请求)。 特洛伊·亨特(Troy Hunt)等人正在使用Cloudflare Workers来识别伪造的密码 。
  • Standard Service Workers API: The power of Cloudflare Workers comes from the ability to run standard JavaScript written against the Service Workers API on Cloudflare's edge nodes around the world.

    标准Service Workers API :Cloudflare Workers的强大功能来自于在全球Cloudflare的边缘节点上针对Service Workers API编写的标准JavaScript的运行能力。

yup, that's how I felt at first; tell me moaar!

y 是的,我一开始就是这样; 告诉我mo

Cloudflare工人的潜力 ( Potential of Cloudflare Workers )

So, the Cloudflare Workers let you run JavaScript in hundreds of data centers around the world. Using a Worker, you can modify your site’s HTTP requests and responses, make parallel requests, or generate responses from the edge.

cloudflare_无服务器Cloudflare员工非常出色_第2张图片

因此,Cloudflare Workers使您可以在全球数百个数据中心中运行JavaScript。 使用工作器,您可以修改站点的HTTP请求和响应,发出并行请求或从边缘生成响应。

Some more examples shared by CoudFlare are:

CoudFlare共享的更多示例是:

  • Load balance between multiple origins to improve speed or reliability.

    多个来源之间的负载平衡以提高速度或可靠性。
  • Render HTML templates while fetching dynamic content from your origin.

    在从源中获取动态内容的同时呈现HTML模板
  • Dynamically respond to requests without connecting to an origin server.

    动态响应请求, 而无需连接到原始服务器
  • Generate parallel requests to different services and combine the responses.

    生成对不同服务的并行请求并组合响应。
  • Create custom security rules and filters to block unwanted visitors and bots.

    创建自定义安全规则和过滤器,以阻止有害的访问者和漫游器。
  • Perform data sanitization & validation before sending a request to origin.

    在发送请求到原始位置之前执行数据清理和验证
  • Decide which requests are cacheable to improve cache hit rate.

    确定哪些请求可缓存以提高缓存命中率
  • Deploy fast fixes in secs without having to update your origin server.

    数秒内即可部署快速修复 ,而无需更新原始服务器。

All of these actions happen inside Cloudflare’s network. Yes, your code will be deployed to hundreds of data centers around the world returning responses to your users faster than your origin ever could. You get all the speed and security of Cloudflare CDN with all the power of JavaScript.

所有这些动作都在Cloudflare的网络内部发生。 是的,您的代码将被部署到世界各地的数百个数据中心,以比您的来源更快的速度向用户返回响应。 借助JavaScript的所有功能,您将获得Cloudflare CDN的所有速度和安全性。

Cloudflare工人示例 ( Cloudflare Workers Examples )

Let's create a couple of simple Cloudflare Workers to see what we can accomplish. Test out Workers free of charge on cloudflareworkers.com.

让我们创建几个简单的Cloudflare Workers,看看我们能完成什么。 在cloudflareworkers.com上免费测试工作者。

#1 Hello World示例 (#1 Hello World Example)

addEventListener('fetch', event => {
  event.respondWith(new Response('Hello World; Learning Cloudflare Workers, eh?!'));
})

cloudflare_无服务器Cloudflare员工非常出色_第3张图片 Test this
example here →

在此处测试此示例→

#2阻止进入特定国家 (#2 Block Access to Specific Countries)

You can enable IP Geolocation to have Cloudflare geolocate visitors to your website and pass the country code to you in ISO 3166-1 Alpha 2 format. That sends the country code to a Cloudflare Worker in the form of a header called cf-ipcountry — we can play around with it to block access on a specific service or API to a country.

您可以启用IP 地理定位,以使Cloudflare可以将访问者地理定位到您的网站,并以ISO 3166-1 Alpha 2格式将国家/地区代码传递给您。 这会将国家/地区代码以称为cf-ipcountry的标头形式发送给Cloudflare工作者-我们可以使用它来阻止特定服务或API对某个国家/地区的访问。

/**
 * CloudFlare Worker.
 *
 * Block access to given countries.
 */
addEventListener('fetch', event => {
    event.respondWith(block(event.request));
});

// Add countries to this Set to block them.
const countries = new Set([
    'US', // United States.
    'SG', // Singapore.
    'BR', // Brazil.
    'PK', // Pakistan.
    'NG' // Nigeria.
]);

/**
 * Block requests.
 *
 * @param {*} request User's request.
 */
async function block(request) {
    // Get country value from request headers.
    const country = request.headers.get('cf-ipcountry');

    // Find out if country is on the block list.
    const isCountryBlocked = countries.has(country);

    // If it's on the blocked list, give back a 403.
    if (isCountryBlocked) {
        return new Response(`SORRY: This page not available in your country!`, {
            status: 403,
            statusText: 'Forbidden'
        });
    }

    // Catch-all return of the original response.
    return await fetch(request);
}

cloudflare_无服务器Cloudflare员工非常出色_第4张图片 Test this
example here →

在此处测试此示例→

#3给予购买力平价(PPP)折扣 (#3 Give Purchasing Power Parity (PPP) Discounts)

I teach a course on VSCode Power User where I offer Purchasing Power Parity (PPP) discounts to developers from countries where the economy is not as strong as the US and many others. There's up to 60% discount available. While building PPP is a whole another debate, you can very easily see how Cloudflare Workers can help here.

我在VSCode Power User上开设了一门课程,向经济不如美国和其他许多国家强劲的国家的开发人员提供购买力平价(PPP)折扣。 有高达60%的折扣。 尽管构建PPP完全是另一场辩论,但您可以很容易地看到Cloudflare Workers如何在这里提供帮助。

Down here, I have built a simple model that checks user's country to respond back with a discount percentage — which ofcoruse can be used to configure a DOM element or another API as a whole.

在这里,我建立了一个简单的模型,该模型可以检查用户所在的国家/地区以打折百分比进行响应-ofcoruse可以用于整体配置DOM元素或其他API。

/**
 * CloudFlare Worker.
 *
 * Purchasing Power Parity Discounts.
 */
addEventListener('fetch', event => {
    event.respondWith(pppDiscount(event.request));
});

// Country with percentage of discount.
const discount = {
    UK: 10,
    CA: 20,
    PK: 60,
    NG: 60,
    IN: 60,
    BR: 60
};

/**
 * Give Purchasing Power Parity Discounts.
 *
 * @param {*} request User's request.
 */
async function pppDiscount(request) {
    // Get country value from request headers.
    const country = request.headers.get('cf-ipcountry');

    const yourDiscount = discount[country];

    // If no discount.
    if (yourDiscount === undefined) {
        return new Response(`No Purchasing Power Parity Discount in your country.`);
    } else {
        // Return discount.
        return new Response(`Purchasing Power Parity Discount in ${country}: ${yourDiscount} percent.`);
    }
}

cloudflare_无服务器Cloudflare员工非常出色_第5张图片 Test this
example here →

在此处测试此示例→

轮到你 ( Your Turn )

Go ahead and try out Cloudflare Workers. I for one am a big fan of workers and have just booked myself a subdomain via Workers.dev (tip: try double-clicking anywhere on the page and see what happens). You should also check out the documentation as well as the Cloudflare Worker Recipes.

继续尝试Cloudflare Workers。 我是一个非常喜欢工作的人,并且刚刚通过Workers.dev为自己预订了一个子域(提示:尝试双击页面上的任意位置,看看会发生什么)。 您还应该查看文档以及《 Cloudflare Worker食谱》 。

I hope you enjoyed the piece. Reach out (and say Hi) on Twitter if you'd like to chat about this. Peace! ✌️

我希望你喜欢这首乐曲。 如果您想聊天,请在Twitter上联系(并打个招呼)。 和平! ✌️

翻译自: https://scotch.io/tutorials/serverless-cloudflare-workers-are-pretty-awesome

cloudflare

你可能感兴趣的:(网络,java,python,大数据,http)