Computer >> 컴퓨터 >  >> 프로그램 작성 >> Redis

Fastly Compute에서 Redis 사용

  • 이 예에서는 이전 버전의 Fastly CLI를 사용합니다. 이 문서에서 최신 버전을 확인하세요.

이 게시물에서는 Fastly Compute@Edge에서 실행되는 간단한 애플리케이션을 작성합니다. 애플리케이션은 페이지 조회수를 추적하기 위해 Upstash Redis에 액세스합니다.

동기

엣지 컴퓨팅은 최근 몇 년 동안 가장 흥미로운 트렌드 중 하나입니다. Cloudflare 및 Fastly와 같은 CDN 서비스는 사용자가 에지 인프라에서 애플리케이션을 실행할 수 있도록 하기 시작했습니다. 이는 개발자가 전 세계적으로 분산된 고성능 애플리케이션을 구축하는 데 도움이 됩니다.

Compute@Edge는 Fastly의 서버리스 플랫폼입니다. Rust, AssemblyScript, Javascript로 코드를 작성하고 Fastly의 에지 네트워크에서 실행할 수 있습니다. Fastly Compute 함수는 상태 비저장입니다. 즉, 개발자는 애플리케이션 상태를 외부 저장소에 유지해야 합니다. 그러나 Fastly는 WebAssembly를 함수의 런타임으로 사용하며 TCP 연결을 허용하지 않습니다. Upstash Redis는 REST API, 글로벌 복제 및 서버리스 가격으로 Fastly Compute 기능을 위한 완벽한 솔루션입니다.

코드 및 데모 보기

프로젝트 설정

Upstash 콘솔에서 데이터베이스를 생성합니다. 엣지 로케이션에서 대기 시간이 짧은 글로벌 데이터베이스를 선호합니다.

빠른 설치 CLI:

brew install fastly/tap/fastly

Fastly 계정으로 CLI 구성:

fastly configure

폴더를 만들고 fastly compute init를 실행하여 프로젝트를 초기화합니다. 폴더 내부:

➜  using-fastly-compute git:(master) ✗ fastly compute init

Creating a new Compute@Edge project.

Press ^C at any time to quit.

Name: [using-fastly-compute]

Description:

Author: [enes@upstash.com]

Language:

[1] Rust
[2] AssemblyScript (beta)
[3] JavaScript (beta)
[4] Other ('bring your own' Wasm binary)

Choose option: [1] 3

Starter kit:
[1] Default starter for JavaScript
    A basic starter kit that demonstrates routing, simple synthetic responses and
    overriding caching rules.
    https://github.com/fastly/compute-starter-kit-javascript-default
Choose option or paste git URL: [1]

✓ Initializing...
✓ Fetching package template...
✓ Updating package manifest...
✓ Initializing package...

Initialized package using-fastly-compute to:

	/Users/enes/dev/examples/using-fastly-compute

To publish the package (build and deploy), run:
	fastly compute publish
To learn about deploying Compute@Edge projects using third-party orchestration tools, visit:
	https://developer.fastly.com/learning/integrations/orchestration/
SUCCESS: Initialized package using-fastly-compute

upstash-redis 및 비행 경로 설치:

npm install @upstash/redis flight-path

다음 플러그인을 추가하여 webpack.config.js를 업데이트하십시오.

plugins: [
    // Polyfills go here.
    // Used for, e.g., any cross-platform WHATWG,
    // or core nodejs modules needed for your application.
    new webpack.ProvidePlugin({
        URL: "core-js/web/url",
    }),
],

fastly.toml 파일 업데이트:

authors = ["enes@upstash.com"]
description = "Example of using Upstash with Fastly Compute@Edge"
language = "javascript"
manifest_version = 2
name = "fastly-upstash"
service_id = "PASTE_YOUR_SERVICE_ID"

[local_server.backends.upstash-db]
url = "https://eu1-liberal-cat-30162.upstash.io"

Fastly Compute 서비스를 생성하고 위에 Fastly 서비스 ID를 붙여넣어야 합니다.

Fastly Compute에서 Redis 사용

또한 Upstash REST URL을 Fastly Compute Service에 백엔드로 추가해야 합니다. Fastly Compute를 사용하려면 외부 네트워크 연결을 백엔드로 등록해야 합니다. 서비스 화면에서 Edit Configuration을 클릭합니다.> Clone version x to edit> Origins> Create a host

호스트를 추가한 후 편집 아이콘을 클릭하여 호스트 이름을 추가합니다. 이름을 upstash-db로 설정합니다. backend와 동일합니다. upstash-redis 클라이언트를 구성하는 동안 옵션. https:// 제거 URL의 일부입니다. 마지막으로 Activate를 클릭합니다. 현재 배포로 구성을 활성화하려면 오른쪽 상단 모서리에 있는 버튼을 누릅니다.

Fastly Compute에서 Redis 사용

Local_server.backends.upstash-db 함수를 로컬에서 실행하려면 가 필요합니다. url을 Upstash 데이터베이스의 REST URL로 바꾸십시오.

구현

src/index.js는 서버리스 기능의 구현입니다. 코드를 아래와 같이 수정합니다.

import { Router } from "flight-path";
import { Redis } from "@upstash/redis/fastly";

const router = new Router();

const redis = new Redis({
  url: "PASTE_YOUR_UPSTASH_REST_URL",
  token: "PASTE_YOUR_UPSTASH_TOKEN",
  backend: "upstash-db",
});

router.get("/", async (req, res) => {
  const count = await redis.incr("count");
  res.send(`Fastly with Upstash! Count: ${count}`);
});

router.listen();

Upstash 콘솔에서 REST URL과 토큰을 복사하여 붙여넣어야 합니다.

upstash-redis 클라이언트를 사용하여 Upstash에 연결하기만 하면 됩니다. 카운터를 증가시키고 응답을 반환합니다.

다른 Redis 클라이언트는 Fastly Compute에서 지원하지 않는 TCP 연결을 사용하므로 사용할 수 없습니다.

auth()로 인증하는 동안 , backend: upstash-db를 추가해야 합니다. 추가 요청 옵션으로. Fastly Compute를 사용하려면 외부 네트워크 연결을 백엔드로 등록해야 하기 때문에 이 작업이 필요합니다.

로컬로 실행

다음을 통해 로컬에서 함수를 실행할 수 있습니다.

fastly compute serve

구축 및 배포

다음을 사용하여 함수를 빌드하고 배포하세요.

fastly compute publish

귀하의 애플리케이션은 Fastly에서 구축 및 배포됩니다. 이 명령은 URL을 기록하므로 작동하는지 테스트할 수 있습니다.

https://horribly-organic-spider.edgecompute.app

닫는 말

이 기사에서는 Upstash를 사용하여 Edge에서 Fastly Compute에서 실행되는 매우 간단한 애플리케이션을 만들었습니다. 우리는 귀하의 피드백을 통해 Upstash와 콘텐츠를 개선하는 것을 좋아합니다. Twitter나 Discord에서 여러분의 생각을 알려주세요.

https://developer.fastly.com/learning/compute/

https://developer.fastly.com/learning/compute/javascript/