💧

Elixir

Fiteny fandaharana

Fiteny fandaharana miasa ho an'ny fananganana rindranasa azo ampitomboina sy karakaraina

Lazan'ny fampidirana

fanapariahana: 2-5 minitra
sokajy: Fiteny fandaharana
RAM ambany indrindra: 512MB
MANAMPY: Tickets sy mailaka

Zarao ity toro-làlana ity

Topy maso

Elixir dia fiteny programming dinamika sy fonctionnel natao hamoronana fampiharana azo ampitomboina, azo tazonina ary mahatohitra hadisoana. Naorina eo ambonin'ny Erlang VM (BEAM) efa voaporofo, Elixir dia mampifangaro ny fahombiazana sy ny fahaiza-manao maoderina amin'ny fahamarinana sy ny modely concurrency izay nanohana rafitra telecom nandritra ny 30 taona mahery. Raha mamorona fampiharana web, rafitra mifandray amin'ny fotoana tena izy, rafitra mizara, na zavatra mitaky high availability sy latency ambany ianao, Elixir dia safidy tsara.

Ny tena manavaka an'i Elixir dia ny modely concurrency mahery izay mampiasa processus maivana. Afaka mamorona processus an-tapitrisany amin'ny milina iray ianao, samy misaraka amin'ny hafa, mifandray amin'ny alalan'ny fandefasana hafatra. Izany dia mahatonga ny fanoratana fampiharana mikarakara an-kolaka ho tsotra tsy misy fanahiana momba ny lock, mutex na race condition. Misaraka ny processus tsirairay, ka tsy mamafy ny hadisoana: ny fanoniana "let it crash" dia midika fa ny rafitrao mivelatra ho azy amin'ny alalan'ny supervision tree.

Ny syntaxe Elixir dia madio, nalaina tamin'ny Ruby, ary mahazo aina, ka mahafinaritra ny manoratra sy mora vakiana. Ny fiteny dia mampitsiry ny immutability sy ny modely programming mifototra amin'ny fonction, izay mahatonga ny kaody ho mora tsaroana sy andramana kokoa. Ny pattern matching dia endri-javatra fototra izay mahatonga ny fikarakarana angona sarotra ho madio sy fohy. Ny operatera pipe mamela ny fanarahana fiantsoana fonction amin'ny fomba azo vakiana, avy eo ankavia, toy ny fisainanao momba ny fiovan'ny angona.

Ny Phoenix Framework dia ny application lehibe indrindra an'i Elixir amin'ny fampandrosoana web. Manome fahombiazana mitovy amin'ny Rails sy fahombiazana mifanandrify amin'ny fiteny compiled, ary mahazo WebSocket an-tapitrisany amin'ny server tokana. Ny Phoenix LiveView dia mamela ny fananganana traikefa mpampiasa mivelatra amin'ny fotoana tena izy tsy misy JavaScript, mampandeha fanavaozana avy amin'ny server ho any amin'ny client amin'ny fomba mora. Miaraka amin'ny fanohanana natiora ho an'ny channel, presence tracking ary pub/sub, Phoenix dia mahatonga ny endri-javatra amin'ny fotoana tena izy izay sarotra any amin'ny fiteny hafa ho mora.

Ny fitaovana Elixir dia tsara indrindra. Mix dia ny fitaovana build natiora izay manao ny zava-drehetra: mamorona tetikasa, mitantana fiankinana, manao fitsapana, mandroso kaody ary mamorona documentation. ExUnit dia manome framework fitsapana matanjaka miaraka amin'ny fanohanana tsara ho an'ny fitsapana mitovy sy asa asynchronous. IEx (Interactive Elixir) dia manome REPL mahery hijerena kaody, debugging, ary na dia fanovana kaody mivantana amin'ny rafitra famokarana aza tsy misy fotoana fijanona.

Ny framework OTP (Open Telecom Platform) izay misy ao amin'ny Erlang dia manome abstraction efa voaporofo ho an'ny fananganana rafitra mizara sy mahatohitra fahadisoana. GenServer, Supervisor ary Application dia manome pattern efa voaporofo ho an'ny fitantanana fanjakana, fikarakarana tsy fahombiazana ary fandaminana fampiharana. Izany dia midika fa tsy fiteny ihany no azonao, fa fahaiza-manao tamin'ny taonjato maro amin'ny fananganana rafitra azo itokisana natao ao amin'ny platform.

Elixir dia mahay amin'ny fananganana rafitra mizara. Ny BEAM VM dia manana fanohanana natiora ho an'ny computing mizara, izay mahatonga ny fampifandraisana node maro sy ny fampifanarahana ny asa amin'ny milina samihafa ho mora. Ny endri-javatra toy ny task mizara, fisoratana processus manerana izao tontolo izao, ary fahaiza-mampifandray cluster natiora dia midika fa azonao atao ny mitombo horizontal amin'ny ezaka kely indrindra. Miaraka amin'ny tranom-boky toy ny libcluster ho an'ny fananganana cluster ho azy, Elixir dia mahatonga ny computing mizara ho azo idirana.

Ny vondrom-piarahamonina dia mavitrika sy mandray vahiny, miaraka amin'ny antontan-taratasy tsara, forum mavitrika, ary package open-source an-tapitrisany amin'ny alalan'ny Hex.pm. Ny orinasa lehibe toy ny Discord, Pinterest, Moz ary Bleacher Report dia mampiasa Elixir ao amin'ny famokarana, izay manaporofo ny fahaiza-manao amin'ny haben'ny lehibe. Na mamorona fampiharana web kely na rafitra mizara lehibe ianao, Elixir dia manome fitaovana hanorenana azy tsara.

Famaritana fototra

Concurrency mivelatra

Processus maivana sy modely actor mahatonga fiasa an-tapitrisany mitovy andro miaraka amin'ny latency ambany

Fahatoniana amin'ny fahadisoana

Supervision tree sy filozofia 'let it crash' mamorona rafitra mihamelona tena izy izay mahavoa amin'ny tsy fahombiazana

Phoenix Framework

Framework web mahomby be dia be miaraka amin'ny endri-javatra amin'ny fotoana tena izy, LiveView, ary fahombiazana mifanandrify amin'ny fiteny compiled

Programming mifototra amin'ny fonction

Angon-drakitra tsy miovaova, pattern matching, ary fitambarana fonction ho an'ny kaody azo tazonina sy mahatohitra hadisoana

Computing mizara

Fanohanana natiora ho an'ny rafitra mizara miaraka amin'ny clustering natiora sy fifandraisana eo amin'ny node

Fanakalozana kaody mihetsika

Manavao ny rafitra famokarana mihetsika tsy misy fijanona na fandavana fifandraisana

Fomba fampiasana

• Fampiharana web amin'ny fotoana tena izy: Mamorona app chat, fitaovana mifandray, dashboard ara-potoana miaraka amin'ny Phoenix Channels sy LiveView
• Server API: API REST sy GraphQL avo fahombiazana mikarakara fangatahana an-tapitrisany miaraka amin'ny latency ambany
• Rafitra mizara: Mikraoserivisy, maritrano mifototra amin'ny hetsika, ary computing mizara miaraka amin'ny clustering natiora
• Fikarakarana asa ambadika: Filaharana asa azo itokisana miaraka amin'ny Oban ho an'ny fandaharam-potoana, fanandramana indray ary fanodinana asa mizara
• Serivisy WebSocket: Lalao multiplayer amin'ny fotoana tena izy, vaovao siport mivantana, tetezan-data ara-bola miaraka amin'ny fifandraisana an-tapitrisany mitovy andro
• IoT sy rafitra embedded: Mitantana fitaovana IoT an-tapitrisany miaraka amin'ny Nerves ho an'ny Linux embedded amin'ny Raspberry Pi sy hardware mitovy
• Rafitra telecom: Fanondroana antso, rafitra fandefasana hafatra ary serivisy high-availability (fampiasana tany am-boalohany an'ny Erlang)

Toro-làlana fametrahana

Fametrahana amin'ny Ubuntu VPS:

1. Apetraho 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. Apetraho 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. Apetraho PostgreSQL (ho an'ny fampiharana miankina amin'ny 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. Apetraho Node.js (ho an'ny fanangonana asset 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. Mamorona ny fampiharana Phoenix voalohany:
# 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. Idirao ny fampiharanao:
Visit: http://localhost:4000
7. Apetraho ho an'ny famokarana (serivisy 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
Ampio ity configuration ity:
[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. Atombohy ny serivisy famokarana:
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. Apetraho proxy famerenana Nginx:
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. Apetraho SSL amin'ny Let's Encrypt:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d yourdomain.com

Torohevitra momba ny kirakira

Configuration ilaina:

1. Configuration tetikasa 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. Configuration 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. Configuration endpoint 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. Configuration 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. Configuration 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. Ohatra 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 ho an'ny fitantanana fanjakana:
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. Hazo 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. Configuration fitsapana:
# 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. Fomba tsara ho an'ny fahombiazana sy famokarana:
- Ampiasao release ho an'ny fametrahana (fa tsy mix phx.server amin'ny famokarana)
- Ahafaho ny pooling fifandraisana miaraka amin'ny pool_size mety
- Apetraho ny level logging mety (info amin'ny famokarana, debug amin'ny dev)
- Ampiasao multi an'i Ecto ho an'ny transaction database
- Ampiharo ny rate limiting amin'ny Plug.RateLimiter na Hammer
- Ampiasao Phoenix.Tracker ho an'ny presence mizara
- Ahafaho ny clustering amin'ny libcluster ho an'ny fitomboana horizontal
- Jereo amin'ny Telemetry sy fitaovana toy ny AppSignal na New Relic

Fandraisana an-tànana ara-teknika

Fandraisana an-tànana

  • Fahatsiarovana: 512RAM 1 MB

Omeo isa ity lahatsoratra ity

★★★★★
-
Maka...

Vonona ny hametraka ny fampiharanao ve ianao? Elixir?

Manomboka ao anatin'ny minitra vitsy amin'ny alalan'ny fizotry ny fametrahana tsotra VPS

Mandefa amin'ny manodidina ny 2 minitra • Full root access • Fanohanana amin'ny alalan'ny tapakila sy mailaka