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

Làm chủ Giám sát Microservice: Cấu trúc Dữ liệu với Namespaces

Kiến trúc Microservice Là Gì?

Kiến trúc microservice là software design pattern nơi chúng ta viết ứng dụng bằng cách kết hợp một vài chương trình nhỏ. Những chương trình này, gọi là microservices, làm việc cùng nhau cho mục tiêu chung. Với một số team, viết vài ứng dụng nhỏ tốn ít thời gian và effort hơn một ứng dụng lớn đơn lẻ.

Dự án microservice-oriented bao gồm một chòm sao các ứng dụng nhỏ, mỗi cái làm phần của nó, chạy trong process riêng, và giao tiếp với phần còn lại qua standardized interfaces. Cách tiếp cận này cho phép team chọn tool tốt nhất cho từng vấn đề mà không commit vào một language hay framework. Nó cũng cho phép chia việc cho các nhóm chuyên biệt hơn.

Từ Monolith đến Microservice

Trong phần đầu series này, chúng ta nói về monoliths. Monoliths dễ bắt đầu. Tuy nhiên, development pace scale kém, chủ yếu vì mọi thứ coupled chặt chẽ. Thậm chí thay đổi code nhỏ cũng force rebuild và test toàn bộ project, dẫn đến release cycles chán nản dài.

Làm sao từ monolith đến microservice? Xem case của Amazon. Một thời gian trước, họ bắt đầu như monolith và dần chuyển sang microservices. Thiết kế ban đầu có thể trông như sau:

Tất nhiên, tôi oversimplify ở đây, nhưng tôi tin tôi đã cover hầu hết basic. Nếu họ chọn microservice pattern từ đầu? Họ sẽ split application by function, mỗi component focus vào một vấn đề.

Họ cũng sẽ cần định nghĩa interfaces và protocols cho inter-service communication, thường với lightweight mechanism như RESTful APIs.

Namespaces Là Gì

Thiết kế microservice có set challenge độc đáo. Chính cái chính có lẽ là instrumentation và error reporting. Nghĩ xem, chúng ta giám sát chục hoặc hàng trăm component phân tán trên các platform và language khác nhau. Và chúng ta phải somehow keep an eye trên tất cả, và đồng thời, tránh mất big picture. Namespaces có thể giúp focus group loosely-coupled microservices thành một bức tranh coherent.

Trong AppSignal, namespaces là containers cho collected metrics. AppSignal dùng ba namespaces mặc định (web, background, và frontend), nhưng chúng ta có thể tạo自己的 bằng cách thêm vài dòng code. Chúng ta sẽ xem chúng hoạt động như thế nào.

Một Application Quản Lý Tất Cả (One Application to Rule Them All)

Khi thiết lập microservice component, điều đầu tiên là cấu hình common application name và environment. Do đó, AppSignal trình bày tất cả collected metrics và alerts trên cùng dashboard.

Chi tiết cụ thể cấu hình giá trị này phụ thuộc vào language và integration. Ví dụ, cấu hình Ruby on Rails app dùng name "Nozama":

# config/appsignal.yml production: active: true push_api_key: "YOUR APPSIGNAL API KEY" name: "Nozama"

Rất tương tự cách cấu hình Elixir integration:

# config/config.exs config :appsignal, :config, active: true, name: "Nozama", push_api_key: "YOUR APPSIGNAL API KEY", env: "production"

Trong Node.js, chúng ta dùng:

const { Appsignal } = require("@appsignal/nodejs"); const appsignal = new Appsignal({ active: true, name: "Nozama", apiKey: "YOUR APPSIGNAL API KEY", });

Cho frontend JavaScript integration, dùng @appsignal/javascript:

import Appsignal from "@appsignal/javascript"; export default new Appsignal({ name: "Nozama", key: "YOUR FRONTEND API KEY", });

Bạn tìm info install và cấu hình AppSignal ở đây:

  • Adding new applications
  • Configuring applications

Dùng Namespaces trong Microservices

Hãy xem chúng ta code từng microservice như thế nào. Bắt đầu với billing system; dùng Elixir và Phoenix cho phần này.

Sau khi follow Phoenix integration setup, chúng ta có thể bắt đầu làm việc trên controllers. Snippet sau set namespace thành billing:

# in a Phoenix controller, we use plug to run the namespace initialization defmodule BillingPageController.PageController do use BillingPageController, :controller plug :set_appsignal_namespace defp set_appsignal_namespace(conn, _params) do # Sets all actions in this controller to report in the "billing" namespace Appsignal.Transaction.set_namespace(:billing) conn end # rest of the controller ... end

Data sẽ xuất hiện trong dashboard khi microservice chạy và controller thấy activity.

Tất nhiên, billing không đưa chúng ta xa trừ khi người mua thứ gì. Đây là vấn đề chúng ta tackle trong microservice riêng. Theo cùng pattern, viết Phoenix application mới với PayButtonController controller bắt đầu như sau:

defmodule PayButtonController.PageController do use PayButtonController, :controller plug :set_appsignal_namespace defp set_appsignal_namespace(conn, _params) do Appsignal.Span.set_namespace(Appsignal.Tracer.root_span(), "pay_button") conn end # rest of the controller ... end

Bây giờ chúng ta có hai namespaces trong dashboard. Dùng cùng name và environment đảm bảo data từ PayButtonController hiển thị cùng BillingPageController, dù là separate applications chạy trên machine khác nhau.

Component tiếp theo là recommendation engine. Implement API endpoint show product suggestions với Express. Set namespace trong Node.js như sau:

app.get("/", (req, res) => { const tracer = appsignal.tracer(); tracer.withSpan( tracer.createSpan({ namespace: "recommendations" }), (span) => { // code to measure goes here span.close(); } ); });

Chúng ta đã lên tới ba namespaces.

Mobile và frontend teams có thể muốn log errors trong dashboard. AppSignal's JavaScript integration tự động assign incoming data với frontend namespace. Nhưng chúng ta có thể đổi như sau:

try { // code that might fail } catch (error) { // handle the error // send error to AppSignal appsignal.sendError(error, {}, "Mobile"); }

Sau một lúc, data sẽ xuất hiện trong namespace Mobile.

Ví dụ show plain JavaScript, nhưng có thể cần additional setup steps nếu dùng frontend framework như React hay Angular.

Cho website, thử Ruby on Rails, MVC framework nổi tiếng AppSignal integrate out-of-the-box. Khởi động Rails controllers với snippet sau set namespace thành homepage:

# in Rails we use before_action callback to change # the namespace before the request starts class HomepageController < ApplicationController before_action :set_appsignal_namespace def set_appsignal_namespace Appsignal.set_namespace("homepage") end # controller actions ... end

Tiếp theo, dùng API endpoints serve data cho website và mobile app. Cho này, dùng Grape, lightweight REST API framework cho Ruby. Lần này, cấu hình AppSignal mất chút effort hơn.

Sau khi cấu hình Ruby integration trong ´config/appsignal.yml´, như trước, bạn có thể bắt đầu log events và metrics với:

Appsignal.start_logger Appsignal.start

Sau đó, insert AppSignal middleware vào error handler chain:

require "appsignal" require "appsignal/integrations/grape" class API < Grape::API insert_before Grape::Middleware::Error, Appsignal::Grape::Middleware resource :search do desc 'return a product search' before do Appsignal.set_namespace("search") end get :product do # product search logic end end end

Cho thêm ví dụ, check Grape integration docs.

Để complete picture, kết thúc với Sidekiq background job. Sidekiq là popular job processor cho Ruby và đây là cách start nó ở standalone mode sau khi cấu hình ´config/appsignal.yml´:

# config.ru require 'appsignal' Sidekiq.on(:startup) do Appsignal.start end Sidekiq.on(:shutdown) do Appsignal.stop('Sidekiq shutdown') end

AppSignal tự động assign data từ jobs vào background namespace. Chúng ta có thể muốn đổi thành namespace specific hơn.

require 'sidekiq' require 'appsignal' class PlainOldRuby include Sidekiq::Worker def perform() Appsignal.set_namespace("urgent_background") # job logic end end

Thu thập Metrics với Standalone Agent

Standalone agent thu thập resource utilization metrics từ bất kỳ Ubuntu, RedHat, hoặc CentOS machine. Chúng ta dùng agent giám sát satellite servers cung cấp facilities như databases, gateways, hoặc message brokers cho microservice applications.

Trong AppSignal chúng ta dùng agent giám sát Kafka servers của chúng tôi. Agent cũng handy cho custom instrumentation trên language và framework không directly supported.

Để bắt đầu với agent, download và install theo installation instructions.

Khi chạy, chúng ta cần edit config file để set API key, application name, và environment. Dùng cùng values dùng trong phần còn lại của microservice để get everything lên one dashboard.

# /etc/appsignal-agent.conf push_api_key = "YOUR APPSIGNAL API KEY" app_name = "Nozama" environment = "production" 

Kết luận

Namespaces là cách tuyệt vời organize data phân tán trong multiple systems. Chúng cũng cho phép cấu hình notifications và fine-tune alert handling. Để xem cách hoạt động, check phần đầu series này.

Additional reads:

  • What can you do with namespaces?
  • Monitoring Any System with StatsD and AppSignal's Standalone Agent
  • Improved host metrics and alerts