Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Redis

Xây dựng ứng dụng Serverless scalable với AWS Lambda & Redis Enterprise Cloud

Trong bài viết này, bạn sẽ học cách tích hợp AWS Lambda và Redis Enterprise Cloud. Sử dụng sample movie-database application, bạn sẽ khám phá cách build và deploy 2 Lambda functions, một Node.js, một Python. Hai functions này tương tác với Redis database để insert, update, delete, và query. Ứng dụng dùng RediSearch API cung cấp rich query và search functionalities. Serverless, dùng AWS Lambda, phù hợp xu hướng microservice architectures vì cho phép developer giảm scope của business "service" thành project nhỏ implement bằng ngôn ngữ programming tùy chọn. Để tìm hiểu thêm, xem video dưới và đọc overview nhanh AWS Lambda và deep dive xây dựng ứng dụng dùng Redis Enterprise Cloud và Lambda:

Nhìn nhanh AWS Lambda

Nếu chưa quen AWS Lambda—serverless compute runtime của hãng, còn gọi Function-as-a-Service (FaaS)—đây là cơ bản bạn cần biết. (Chuyên gia Lambda có thể skip sang section tiếp.) AWS Lambda cho phép ứng dụng chạy function on-demand responding đến event cụ thể, cách tốt xây dựng event-driven architecture (EDA) applications. AWS Lambda functions, fully managed bởi AWS, có thể tạo bằng nhiều ngôn ngữ. Phần tốt nhất: developer thường không cần hiểu đầy đủ application lifecycle để dùng.

AWS Lambda có thể invoke bằng vài phương pháp: trực tiếp từ AWS Console, dùng events từ AWS Services khác như SNS, SQS, Kinesis, hoặc từ AWS Console, CloudWatch, S3 events. Trong sample movie-database app, Lambda functions sẽ được invoke dùng HTTP REST endpoint, thông qua AWS API Gateway. (Xem thêm về AWS Lambda function invocation trong documentation.)

Quy trình thực thi HTTP AWS Lambda

Cụ thể, request qua HTTP routed đến AWS API Gateway management tool, parse body, header, parameters, và trigger Lambda function với payload này:

Xây dựng ứng dụng Serverless scalable với AWS Lambda & Redis Enterprise Cloud

Là developer, bạn chỉ viết code expose REST endpoint và cấu hình deployment expose nó trong AWS API Gateway. (Sẽ thảo luận thêm ở section tiếp về sample movie-database app.)

Quản lý state và data trong ứng dụng serverless

AWS Lambda là môi trường stateless. Trong nhiều ứng dụng, bạn vẫn muốn share state giữa services hoặc calls, và Redis giúp. Cho simple state management, AWS developer thường dùng ElastiCache, nhưng nhiều app cần hơn state management, còn cần persistence, rich data, high performance, và query model. Redis Enterprise Cloud cung cấp fully managed service trên AWS (Google Cloud và Microsoft Azure cũng hỗ trợ).

Sample movie-database application Redis

Sẵn sàng xem sample movie-database app để thấy key steps xây dựng app dùng Redis Enterprise Cloud và AWS Lambda.

Ứng dụng dùng dataset documented trong RediSearch Getting Started tutorial, gồm movie catalog, làm từ Redis Hashes. Như biểu đồ dưới, frontend build bằng Vue.js, gọi REST endpoints để:

  • List, sort, filter movies
  • Edit movies và add/delete comments
  • Search movies dùng full-text search và faceted search
Xây dựng ứng dụng Serverless scalable với AWS Lambda & Redis Enterprise Cloud Xây dựng ứng dụng Serverless scalable với AWS Lambda & Redis Enterprise Cloud

Như trên, app tận dụng AWS API Gateway, AWS Lambda, Redis Enterprise Cloud cho datastore. Thêm vào đó, Python service dùng AWS Key Management Service lưu và encrypt Redis database password.

Cài đặt và chạy demo application

Để bắt đầu, cần vài prerequisites:

  • AWS account setup, credentials, CLI Installed
  • Tài khoản Redis Enterprise Cloud và database, với module RediSearch enabled
  • Git
  • Node.js
  • Python
  • Redis command line interface (CLI)

Khi đã có mọi thứ, hãy đi qua quy trình cài và chạy sample app.

Bước 1: Lấy thông tin database Redis Enterprise Cloud

Nếu chưa tạo database trên Redis Enterprise Cloud, hãy làm theo guide Get Started with Redis Modules.

Khi connected đến Redis Enterprise Cloud, tìm database connection info trong web console; chắc chắn thêm module "RediSearch 2" vào database.

Xây dựng ứng dụng Serverless scalable với AWS Lambda & Redis Enterprise Cloud

Bạn cần các properties sau để connect Lambda functions đến Redis database:

  • REDIS_HOST: redis-18541.xxx.xxxx.xxx.cloud.redis.com
  • REDIS_PORT: 18541
  • REDIS_PASSWORD : <mật khẩu hiển thị trên màn hình>

Bước 2: Lấy project từ GitHub

Clone repository về local, move vào project directory

> git clone https://github.com/redis-developer/aws-redis-cloud-demo.git > cd aws-redis-cloud-demo

Cấu trúc project directory:

aws-redis-cloud-demo ├── README.md ├── front-end => Vue.js project │ ├── .env.development => to set the Lambda URLs in dev mode │ ├── .env.production => to set the Lambda URLs in production mode │ ├── ... │ └── vue.config.js │ └── ... ├── movie-comments-microservice => The Python, comments service │ ├── .chalice │ │ └── config.json => Lambda & Service configuration │ ├── app.py │ ├── chalicelib => Contains application code and lib │ │ └── …. │ ├── readme.md │ └── requirements.txt └── movies-list-microservice => The Node.js, movie service ├── import_movies.redis => Dataset file ├── ... ├── serverless.yml => Lambda & Service configuration ├── src │ └── ... └── ...

Bước 3: Import movie-database dataset vào ứng dụng

File aws-redis-cloud-demo/movies-list-microservice/import_movies.redis chứa tất cả Redis commands insert movies vào database. Commands dùng:

  • HSET cho mỗi movie
  • FT.CREATE tạo RediSearch index.

Để import dataset, mở terminal và chạy:

> export REDISCLI_AUTH=<YOUR_DB_PASSWORD> > redis-cli -h redis-18541.xxx.xxxx.xxx.cloud.redis.com \ -p 18541 < movies-list-microservice/import_movies.redis

Bước 4: Cấu hình ứng dụng dùng Redis Enterprise Cloud instance

Trước khi test, phải cấu hình Node.js và Python services với Redis Enterprise Cloud database instance. Mở các file:

  • ./movies-list-microservice/serverless.yml
  • ./movie-comments-microservice/.chalice/config.json

Set Redis host, port, password: (REDIS_HOST, REDIS_PORT, REDIS_PASSWORD)

Bước 5: Build và chạy movie microservice (Node.js)

Làm theo steps dưới để build và run project. (Cũng tìm toàn bộ info trong Readme project.)

  1. Cài serverless framework
> npm install -g serverless

2. Vào movies-list-microservice directory

> cd movies-list-microservice

3. Cài dependencies

> npm install

4. Chạy Lambda function locally

> npm start

5. Test service bằng browser call REST service: https://localhost:3000/api/movies/1

6. Deploy service lên AWS, chạy lệnh deploy function vào AWS environment:

> serverless deploy ................................ Serverless: Stack update finished... Service Information service: movies-list-microservice stage: api region: us-east-1 stack: movies-list-microservice-api resources: 33 api keys: None endpoints: GET - https://<xxx>.execute-api.<reg>.amazonaws.com/api/movies/search GET - https://<xxx>.execute-api.<reg>.amazonaws.com/api/movies/group_by/{field} GET - https://<xxx>.execute-api.<reg>.amazonaws.com/api/movies/{id} POST - https://<xxx>.execute-api.<reg>.amazonaws.com/api/movies/{id} functions: listMovies: movies-list-microservice-api-listMovies searchMovies: movies-list-microservice-api-searchMovies getMovie: movies-list-microservice-api-getMovie saveMovie: movies-list-microservice-api-saveMovie layers: None

7. Test API bằng browser trỏ đến https://<xxx>.execute-api.<reg>.amazonaws.com/api/movies/1

Note: nếu lỗi, check functions log trong AWS CloudWatch xem gì xảy ra.

Deep dive code:

  • File package.json chứa dependencies Node.js project. Project đơn giản, dùng dependencies:
    • Thư viện redis và redis-redisearch connect Redis và expose RediSearch commands.
    • Thư viện aws-lambda gọi AWS Lambda functions deploy node app lên AWS environment.
  • File serverless.yml define serverless functions mapping HTTP actions đến JavaScript function được gọi (defined in handler.ts), và chứa environment variables (chủ yếu Redis connection string trong demo).
  • File handler.ts là class capture event từ AWS Gateway và gọi application library SearchService, làm tất cả calls đến Redis database.
  • File SearchService.ts chứa tất cả methods interact với Redis database và dùng Redis/RediSearch API: client.ft_search(), client.aggregate(), client.hmset(), và hơn nữa. (Tìm hiểu thêm Redis/RediSearch commands tại Redis University và tutorial Getting Started with RediSearch 2.0 trên GitHub.)

Bước 6: Build và chạy comments microservice (Python)

Các steps build và run project. (Cũng tìm info trong Readme project.)

  1. Move đến Python project và tạo virtual environment:
> cd movie-comments-microservice > python3 -m venv chalice-env > source chalice-env/bin/activate

2. Cài dependencies:

> pip install -r requirements.txt

3. Setup AWS environment, chạy lệnh sau và cấu hình ID và Secret:

> aws configure AWS Access Key ID [None]: ****************ABCD AWS Secret Access Key [None]: ****************abCd Default region name [None]: us-west-2 Default output format [None]:

4. Deploy service lên AWS, chạy lệnh deploy function vào AWS environment:

> chalice deploy Reusing existing deployment package. Updating policy for IAM role: movie-comments-microservice-dev Creating lambda function: movie-comments-microservice-dev Creating Rest API Resources deployed: - Lambda ARN: arn:aws:lambda:us-east-1:11111111111:function:movie-comments-microservice-dev - Rest API URL: https://XXXXXXX.execute-api.us-east-1.amazonaws.com/api/

Deep dive code:

  • File requirements.txt chứa dependencies Python project. Project đơn giản, dùng:
    • Chalice là AWS framework tạo serverless applications Python
    • redis và redisearch access Redis và dùng RediSearch API
  • File config.json define serverless app và dùng define environment variables—trong app này, Redis database connection info.
  • File app.py là entry point define tất cả REST endpoints dùng various routes. App import various dependencies, đặc biệt CommentService dùng interact với Redis. Khi muốn dùng multiple files phải đặt files trong folder chalicelib.
  • File comment_service.py chứa tất cả interactions với Redis create, query, delete comments. Điểm thú vị cho feature comment là method search(). Method này retrieve comments cho movie sorted by creation date dùng search_client.search() call.

Tùy chọn, bạn có thể lưu Redis database password trong AWS Key Management Service. Các bước cấu hình trong documentation project.

Bước 7: Chạy frontend application

  1. Vào frontend directory và cài dependencies:
> cd front-end > npm install

2. Edit file .env.development set URL movie và comment services:

VUE_APP_MOVIES_SERVICE=https://<xxx>.execute-api.<reg>.amazonaws.com/api VUE_APP_COMMENTS_SERVICE=https://<xxx>..execute-api.<reg>.amazonaws.com/api

3. Chạy ứng dụng:

> npm run serve

4. Mở browser, vào https://localhost:8084

Bây giờ bạn navigate app, update/search movies, add/delete comments.

Tùy chọn, bạn dùng S3 và CloudFront deploy Vue app trong AWS environment và serve publicly cho users. Giải thích trong documentation project.

Kết luận

Làm việc với AWS Lambda và Redis Enterprise Cloud đơn giản hóa deployment services. Dùng Redis Enterprise Cloud với RediSearch, bạn dễ dàng query Redis data dùng values, cho phép dùng Redis làm main database của services.

Redis Enterprise Cloud compatible với Redis, cho phép migrate dễ dàng existing Redis deployments, cả OSS và managed services. Chỉ cần đổi connection parameters (như database endpoints). Có multiple ways live migration, bao gồm:

  • Blue-green deployments
  • Synchronizing Amazon ElastiCache và Redis Enterprise Cloud dùng Active Passive Geo-Distribution
  • Dùng open source RIOT tool migrate data

Ngoài RediSearch, Redis Enterprise Cloud cho phép dùng các data models hứa hẹn khác như graph, JSON, time series, Bloom filters, và cung cấp nhiều database features quan trọng cho production: high availability, scalability, persistence, security, Active-Active geo-distribution.

Muốn tìm hiểu thêm? Xem AWS re:Invent home page và đọc tutorials/blog posts:

  • Get Started with Redis Modules on AWS
  • 6 Key Features to Consider When Choosing a DBaaS Provider
  • How Redis Enterprise Cloud Meets the Needs of Maturing Enterprise Customers on AWS