💧

Elixir

Lipuo tsa Mananeo

Puo e sebetsang ea mananeo bakeng sa ho aha lits'ebetso tse ka atolosoang le tse ka hlokomeloang

Lintlha tsa ho kenya

Ho romelloa ha basebetsi: 2-5 min
sehlopha: Lipuo tsa Mananeo
RAM e tlase: 512MB
Tšehetso: Litekete le imeile

Tseba lengolo lena

Tlhaloso

Elixir ke puo ea lenaneo e sebetsang, e matla, e rekiloeng ho haha lits'ebetso tse atolohang, tse bolokehang le tse tiisang ho hlōleha. E hahiloe holim'a Erlang VM (BEAM) e leke ka nako, Elixir e kopanya ts'ebetso le ho hlalosa ha lipuo tsa sejoale-joale le botšepehi le mokhoa oa ho sebetsa hammoho o neng o matlafatsa lisistimi tsa mohala lilemong tse fetang 30. Haeba u haha lits'ebetso tsa webo, lisistimi tsa nako ea sebele, lisistimi tse aroloang, kapa ntho efe kapa efe e hlokang ho ba teng ha maemo a phahameng le latency e tlase, Elixir ke khetho e ntle haholo.

Seo se etsang hore Elixir e be ea ikhethang ke mokhoa oa eona o hlollang oa ho sebetsa hammoho o matlafalitsoeng ke li-process tse bobebe. U ka qalisa li-process tse limilione lenaneong le le leng, e 'ngoe le e 'ngoe e arotsoe ho tse ling, e buisanang ka phetisetso ea melaetsa. Sena se etsa hore ho be bonolo ho ngola lits'ebetso tse sebetsang hammoho ka matla ntle le ho tšoenyeha ka lock, mutex kapa race condition. Process e 'ngoe le e 'ngoe e arohane, kahoo ho hlōleha ha e le 'ngoe ha ho hlōle tse ling: mokhoa oa "let it crash" o bolela hore sistimi ea hao e iphetola ka boyona ka li-supervision tree.

Syntax ea Elixir e hlakile, e ts'oana le Ruby, 'me e hlalosa, e etsa hore ho be monate ho ngola le ho bala. Puo e tsepamisa maikutlo ho immutability le mekhoa ea functional programming, e isang khoutung e bonolo ho e nahana le ho e leka. Pattern matching ke karolo e ka sehloohong e etsang hore ho sebetsana le lisebelisoa tse rarahaneng tsa data ho be ntle le ho khutsufatsa. Operator ea pipe e u lumella ho kenya lipiletso tsa ts'ebetso ka tsela e balehang, ho tloha ka le letšehi ho ea ka le letona, e ts'oanang le mokhoa oa ho nahana ka liphetoho tsa data.

Phoenix Framework ke sesebelisoa se kholo sa Elixir bakeng sa nts'etsopele ea webo. E fana ka tsoelo-pele e ts'oanang le Rails ka ts'ebetso e lekanang le lipuo tse hlophisitsoeng, e sebetsana le likhokahano tsa WebSocket tse limilione ho server e le 'ngoe. Phoenix LiveView e u lumella ho haha boiphihlelo ba basebelisi bo phelang, bo matla ntle le ho ngola JavaScript, ho sutumetsa lintlafatso ho tloha server ho ea ho client ka bonolo. Ka tšehetso e kahare ea channels, ho latela boteng le pub/sub, Phoenix e etsa hore likarolo tsa nako ea sebele tse rarahaneng ho lipuo tse ling li be bonolo haholo.

Lisebelisoa tsa Elixir li hloahloa haholo. Mix ke sesebelisoa sa kahare sa ho haha se etsang tsohle: ho theha liprojeke, ho laola li-dependency, ho sebetsa liteko, ho hlophisa khoutu le ho hlahisa litlhaloso. ExUnit e fana ka moralo o matla oa liteko o nang le tšehetso e ntle bakeng sa liteko tse sebetsang hammoho le liketso tsa async. IEx (Interactive Elixir) e fana ka REPL e matla bakeng sa ho hlahloba khoutu, ho lokisa liphoso le ho fetola khoutu ka potlako lisistimeng tsa production ntle le nako e sa sebetseng.

Moralo oa OTP (Open Telecom Platform) o tsamaisang le Erlang o fana ka li-abstraction tse hlahlobiloeng ka nako e telele bakeng sa ho haha lisistimi tse aroloang, tse tiisang ho hlōleha. GenServers, Supervisors le Applications li o fa mekhoa e netefalitsoeng bakeng sa ho laola boemo, ho sebetsana le ho hlōleha le ho haha lits'ebetso. Sena se bolela hore ha u fumane puo feela: u fumana lilemo tsa boiphihlelo ba ho haha lisistimi tse tšepahalang tse kentsoeng sebopehong.

Elixir e hlaha ha ho haha lisistimi tse aroloang. Sistimi ea BEAM VM e na le tšehetso e kahare ea ho bala ka mokhoa o aroloang, e etsang hore ho be bonolo ho kopanya li-node tse ngata le ho hlophisa mosebetsi lipakeng tsa lisistimi tse ngata. Likarolo tse kang mesebetsi e aroloang, ngoliso ea process ea lefats'e lohle le bokhoni ba clustering bo kahare li bolela hore u ka atolosa ka bophara ka boiteko bo fokolang. Ha e kopantsoe le laeborari tse kang libcluster bakeng sa ho haha cluster ka boits'oarelo, Elixir e etsa hore khopolo ea ho bala e aroloang e fumanehe.

Sechaba se mafolofolo 'me se amohela, se nang le litlhaloso tse ntle, lifora tse sebetsang le li-package tse makete a mangata tsa mohloli o bulehileng ka Hex.pm. Mekhatlo e meholo joalo ka Discord, Pinterest, Moz le Bleacher Report e sebelisa Elixir ho production, e netefatsa bokhoni ba eona boholong bo kholo. Hore u haha app ea webo e nyane kapa sistimi e kholo e aroloang, Elixir e u fa lisebelisoa tsa ho e haha ka nepo.

Likarolo tsa bohlokoa

Ho Sebetsa Hammoho ho Atolohang

Li-process tse bobebe le mohlala oa actor li nolofalletsa ts'ebetso e limilione e sebetsang hammoho ka latency e tlase

Ho Tiisa ho Hlōleha

Lifate tsa supervision le khopolo ea 'let it crash' li etsa lisistimi tse iphetolang tse pholohang liphoso

Phoenix Framework

Moralo oa webo o sebetsang hantle ka likarolo tsa nako ea sebele, LiveView, le ts'ebetso e lekanang le lipuo tse hlophisitsoeng

Mokhoa oa Functional Programming

Data e sa fetoheng, pattern matching le kopanyo ea functional bakeng sa khoutu e lokelang ho lula e hlokomeloa le e hanyetsang liphoso

Ho Bala ka Mokhoa o Aroloang

Tšehetso ea kahare bakeng sa lisistimi tse aroloang ka clustering ea semmuso le puisano pakeng tsa li-node

Hot Code Swapping (Ho Fetola Khoutu ha Sistimi e Sebetsa)

Ntlafatsa lisistimi tsa production tse sebetsang ntle le nako e sa sebetseng kapa ho senya likhokahano

Mehlala ea ho sebelisa

• Real-Time Web Applications: Haha li-chat app, lisebelisoa tsa tšebelisano, li-dashboard tse phelang ka Phoenix Channels le LiveView
• API Servers: Li-REST le GraphQL API tse nang le ts'ebetso e phahameng tse sebetsanang le likopo tse limilione ka latency e tlase
• Distributed Systems: Microservices, meralo e tsamaisoang ke liketsahalo le ho bala ka mokhoa o aroloang ka clustering e kahare
• Background Job Processing: Mela ea mesebetsi e tšepahalang ka Oban bakeng sa ho hlophisa linako, ho leka hape le ts'ebetso ea mesebetsi e aroloang
• WebSocket Services: Lipapali tsa multiplayer tsa nako ea sebele, litaba tsa lipapali tse phelang, le li-stream tsa data ea lichelete tse nang le likhokahano tse limilione tse sebetsang hammoho
• IoT & Embedded Systems: Laola li-IoT tse makete a mangata ka Nerves bakeng sa Linux e kentsoeng ho Raspberry Pi le lisebelisoa tse tšoanang
• Telecommunication Systems: Ho khetholla mohala, lipalangoang tsa melaetsa le litšebeletso tse nang le ho fumaneha ho phahameng (sebelisong sa pele sa Erlang)

Litaelo tsa ho kenya

Kenyo ho Ubuntu VPS:

1. Kenya Erlang/OTP:
# Add Erlang Solutions repository
wget https://packages.erlang-solutions.com/erlang-solutions_2.0_all.deb
sudo dpkg -i erlang-solutions_2.0_all.deb
sudo apt update

# Install Erlang (OTP 26)
sudo apt install esl-erlang -y

# Verify installation
erl -eval 'erlang:display(erlang:system_info(otp_release)), halt().'
2. Kenya Elixir:
# Install Elixir via apt
sudo apt install elixir -y

# Verify installation
elixir --version
# Should show: Elixir 1.14+ and Erlang/OTP 26

# Install Hex package manager
mix local.hex --force

# Install Phoenix archive (for Phoenix projects)
mix archive.install hex phx_new --force
3. Kenya PostgreSQL (bakeng sa lits'ebetso tse thehiloeng database):
# Install PostgreSQL
sudo apt install postgresql postgresql-contrib -y

# Start PostgreSQL
sudo systemctl start postgresql
sudo systemctl enable postgresql

# Create database user
sudo -u postgres createuser --superuser $USER
sudo -u postgres psql -c "ALTER USER $USER WITH PASSWORD 'yourpassword';"
4. Kenya Node.js (bakeng sa compilation ea li-asset tsa Phoenix):
# Install Node.js 18
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install nodejs -y

# Verify installation
node --version
npm --version
5. Theha Lits'ebetso tsa Hao ea Pele ea Phoenix:
# Create new Phoenix app
mix phx.new myapp --database postgres

# Navigate to project
cd myapp

# Configure database (edit config/dev.exs if needed)
mix ecto.create

# Install dependencies
mix deps.get

# Start Phoenix server
mix phx.server
6. Fihlella Lits'ebetso tsa Hao:
Visit: http://localhost:4000
7. Hlophisa bakeng sa Production (Tšebeletso ea Systemd):
# Build release
export MIX_ENV=prod
export SECRET_KEY_BASE=$(mix phx.gen.secret)
export DATABASE_URL=ecto://USER:PASS@localhost/myapp_prod

mix deps.get --only prod
mix compile
mix assets.deploy
mix release

# Create systemd service
sudo nano /etc/systemd/system/myapp.service
Kenya litlhophiso tsena:
[Unit]
Description=My Phoenix App
After=network.target

[Service]
Type=simple
User=deploy
Group=deploy
WorkingDirectory=/home/deploy/myapp
Environment="PORT=4000"
Environment="MIX_ENV=prod"
Environment="SECRET_KEY_BASE=your_secret_key"
Environment="DATABASE_URL=ecto://user:pass@localhost/myapp_prod"
ExecStart=/home/deploy/myapp/_build/prod/rel/myapp/bin/myapp start
Restart=on-failure
RestartSec=5
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target
8. Qalisa Tšebeletso ea Production:
sudo systemctl daemon-reload
sudo systemctl start myapp
sudo systemctl enable myapp

# Check status
sudo systemctl status myapp

# View logs
sudo journalctl -u myapp -f
9. Hlophisa Nginx Reverse Proxy:
sudo nano /etc/nginx/sites-available/myapp

# Add this configuration:
server {
    listen 80;
    server_name yourdomain.com;

    location / {
        proxy_pass http://localhost:4000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# Enable site
sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx
10. Hlophisa SSL ka Let's Encrypt:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

Litlhahiso tsa ho kenya

Litlhophiso tse Hlokahalang:

1. Litlhophiso tsa Project ea Mix (mix.exs):
defmodule MyApp.MixProject do
  use Mix.Project

  def project do
    [
      app: :myapp,
      version: "0.1.0",
      elixir: "~> 1.14",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [
      mod: {MyApp.Application, []},
      extra_applications: [:logger, :runtime_tools]
    ]
  end

  defp deps do
    [
      {:phoenix, "~> 1.7"},
      {:phoenix_live_view, "~> 0.20"},
      {:phoenix_ecto, "~> 4.4"},
      {:ecto_sql, "~> 3.10"},
      {:postgrex, ">= 0.0.0"},
      {:phoenix_html, "~> 3.3"},
      {:phoenix_live_reload, "~> 1.4", only: :dev},
      {:jason, "~> 1.4"},
      {:plug_cowboy, "~> 2.6"}
    ]
  end
end
2. Litlhophiso tsa Runtime (config/runtime.exs):
import Config

if config_env() == :prod do
  database_url = System.get_env("DATABASE_URL") ||
    raise "DATABASE_URL not available"

  config :myapp, MyApp.Repo,
    url: database_url,
    pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
    socket_options: [:inet6]

  secret_key_base = System.get_env("SECRET_KEY_BASE") ||
    raise "SECRET_KEY_BASE not available"

  host = System.get_env("PHX_HOST") || "example.com"
  port = String.to_integer(System.get_env("PORT") || "4000")

  config :myapp, MyAppWeb.Endpoint,
    url: [host: host, port: 443, scheme: "https"],
    http: [ip: {0, 0, 0, 0, 0, 0, 0, 0}, port: port],
    secret_key_base: secret_key_base,
    server: true
end
3. Litlhophiso tsa Endpoint ea Phoenix (lib/myapp_web/endpoint.ex):
defmodule MyAppWeb.Endpoint do
  use Phoenix.Endpoint, otp_app: :myapp

  # WebSocket configuration
  socket "/live", Phoenix.LiveView.Socket,
    websocket: [connect_info: [session: @session_options]]

  # Session configuration
  plug Plug.Session,
    store: :cookie,
    key: "_myapp_key",
    signing_salt: "random_salt"

  plug MyAppWeb.Router
end
4. Litlhophiso tsa Database (Ecto):
# config/dev.exs
config :myapp, MyApp.Repo,
  username: "postgres",
  password: "postgres",
  hostname: "localhost",
  database: "myapp_dev",
  stacktrace: true,
  show_sensitive_data_on_connection_error: true,
  pool_size: 10
5. Litlhophiso tsa Router:
defmodule MyAppWeb.Router do
  use MyAppWeb, :router

  pipeline :browser do
    plug :accepts, ["html"]
    plug :fetch_session
    plug :fetch_live_flash
    plug :put_root_layout, {MyAppWeb.Layouts, :root}
    plug :protect_from_forgery
    plug :put_secure_browser_headers
  end

  pipeline :api do
    plug :accepts, ["json"]
  end

  scope "/", MyAppWeb do
    pipe_through :browser

    live "/", HomeLive
    live "/posts", PostLive.Index
    live "/posts/:id", PostLive.Show
  end

  scope "/api", MyAppWeb do
    pipe_through :api

    resources "/users", UserController
    resources "/posts", PostController
  end
end
6. Mohlala oa LiveView:
defmodule MyAppWeb.CounterLive do
  use MyAppWeb, :live_view

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :count, 0)}
  end

  def handle_event("inc", _params, socket) do
    {:noreply, update(socket, :count, &(&1 + 1))}
  end

  def handle_event("dec", _params, socket) do
    {:noreply, update(socket, :count, &(&1 - 1))}
  end

  def render(assigns) do
    # Template with counter and buttons
  end
end
7. GenServer bakeng sa Taolo ea Boemo:
defmodule MyApp.Counter do
  use GenServer

  # Client API
  def start_link(initial_value) do
    GenServer.start_link(__MODULE__, initial_value, name: __MODULE__)
  end

  def increment do
    GenServer.call(__MODULE__, :increment)
  end

  def get_value do
    GenServer.call(__MODULE__, :get_value)
  end

  # Server callbacks
  def init(initial_value) do
    {:ok, initial_value}
  end

  def handle_call(:increment, _from, state) do
    {:reply, state + 1, state + 1}
  end

  def handle_call(:get_value, _from, state) do
    {:reply, state, state}
  end
end
8. Sefate sa Supervision:
defmodule MyApp.Application do
  use Application

  def start(_type, _args) do
    children = [
      MyApp.Repo,
      MyAppWeb.Endpoint,
      {Phoenix.PubSub, name: MyApp.PubSub},
      MyApp.Counter  # Add your GenServer here
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
9. Litlhophiso tsa Liteko:
# test/myapp_web/live/counter_live_test.exs
defmodule MyAppWeb.CounterLiveTest do
  use MyAppWeb.ConnCase
  import Phoenix.LiveViewTest

  test "increments counter", %{conn: conn} do
    {:ok, view, _html} = live(conn, "/counter")

    assert view |> element("h1") |> render() =~ "Counter: 0"

    view |> element("button", "+") |> render_click()

    assert view |> element("h1") |> render() =~ "Counter: 1"
  end
end
10. Mekhoa e Molemo ka ho Fetisisa ea Ts'ebetso le Production:
- Sebelisa releases bakeng sa romello (e seng mix phx.server ho production)
- Nolofalletsa connection pooling ka pool_size e nepahetseng
- Hlophisa boemo bo nepahetseng ba logging (info ho production, debug ho dev)
- Sebelisa multi ea Ecto bakeng sa li-transaction tsa database
- Kenya rate limiting ka Plug.RateLimiter kapa Hammer
- Sebelisa Phoenix.Tracker bakeng sa boteng bo aroloang
- Nolofalletsa clustering ka libcluster bakeng sa ho atolosa ka bophara
- Lekola ka Telemetry le lisebelisoa tse kang AppSignal kapa New Relic

Likopo tsa theknoloji

Litaelo tsa sistimi

  • Khopolo: 512MB RAM

Lekanya Sengoloa sena

★★★★★
-
Ho kenya...

Na o se o loketse ho kenya kopo ya hao? Elixir?

Qala ka metsotsoana ka ts'ebetso ea rona e bonolo ea ho kenya VPS

Ho kenya ka ho ka bang 2 metsotso • Full root ho kena • Thuto ka terene le lengolo tsoibila