Sebagai alternative lain dari socket.io, Laravel Websocket. Centrifugo juga merupakan alternative lebih murah dari service berbayar dari pusher.com atau ably.io. Kekurangan centrifugo dibandingkan service berbayar dari pusher adalah kita harus memonitoring sendiri data yang melewati centrifugo, dari centrifugo sendiri sudah menyediakan exporter untuk prometheus.

Instalasi, konfigurasi centrifugo kurang lebih selesai dalam 20 menit

Setting Subdomain

Kita akan menggunakan subdomain untuk mengakses centrifugo, dan juga akan dipasangi SSL agar lebih aman.
centrifugo subdomain ipv4 ipv6
saya menggunakan IPv4 dan IPv6. Bila server yang anda miliki hanya memiliki IPv4 bisa menggunakan menggunakan IPv4 saja.

Install SSL Letsencrypt

Install SSL dengan letsencryp dengan perintah dibawah ini

apt install socat -y
curl https://get.acme.sh | sh

reload ~/.bashrc

source ~/.bashrc

install ssl untuk subdomain anda disini saya menggunakan centrifugo.jaranguda.com

acme.sh --issue -d centrifugo.jaranguda.com --standalone

tunggu beberapa saat hingga ssl berhasil digenerate

...
...
[Sat 08 Aug 2020 03:49:05 AM UTC] Your cert key is in  /root/.acme.sh/centrifugo.jaranguda.com/centrifugo.jaranguda.com.key 
[Sat 08 Aug 2020 03:49:05 AM UTC] The intermediate CA cert is in  /root/.acme.sh/centrifugo.jaranguda.com/ca.cer 
[Sat 08 Aug 2020 03:49:05 AM UTC] And the full chain certs is there:  /root/.acme.sh/centrifugo.jaranguda.com/fullchain.cer

Update Ubuntu 20.04

sudo apt update
sudo apt upgrade -y

Install Dependency

sudo apt install tar wget -y

Buat User Centrifugo

Untuk menjalankan service centrifugo kita akan membuat user baru dan meletakkan konfigurasi di folder /etc/centrifugo

mkdir /etc/centrifugo
useradd --system -U -M centrifugo -s /bin/false -d /etc/centrifugo

Install Redis

sudo apt install redis -y

jalankan service redis

sudo systemctl enable redis
sudo systemctl start redis

Install Centrifugo

Versi paling baru bisa di download dari halaman rilis centrifugo. Saat ini versi terbaru versi 2.6.1

wget https://github.com/centrifugal/centrifugo/releases/download/v2.6.1/centrifugo_2.6.1_linux_amd64.tar.gz

Ekstrak file yang baru di download

sudo tar zxvf centrifugo_2.6.1_linux_amd64.tar.gz -C /etc/centrifugo/

Copy file executable centrifugo ke /usr/local/bin/ agar bisa dijalankan dari mana saja. Karena /usr/local/bin sudah termasuk didalam $PATH

sudo cp /etc/centrifugo/centrifugo /usr/local/bin/

Generate Konfigurasi Centrifugo

Generate config centrifugo di folder /etc/centrifugo/

cd /etc/centrifugo/
sudo centrifugo genconfig

Buat folder untuk file SSL

sudo mkdir /etc/centrifugo/ssl

copy file ssl ke folder diatas

sudo cp /root/.acme.sh/centrifugo.jaranguda.com/centrifugo.jaranguda.com.key /etc/centrifugo/ssl/
sudo cp /root/.acme.sh/centrifugo.jaranguda.com/fullchain.cer /etc/centrifugo/ssl/

ubah hak akses /etc/centrifugo

chown centrifugo:centrifugo -R /etc/centrifugo

jalankan centrifugo

sudo centrifugo --config /etc/centrifugo/config.json --admin --health --redis_host 127.0.0.1 --redis_port 6379 --tls --tls_cert /etc/centrifugo/ssl/fullchain.cer --tls_key /etc/centrifugo/ssl/centrifugo.jaranguda.com.key

ganti domain centrifugo.jaranguda.com menjadi domain anda.

buka di browser https://DOMAIN:8000
centrifugo https
Untuk lebih memudahkan kita akan merubah command line tersebut menjadi file konfigurasi config.json, ubah file /etc/centrifugo/config.json menjadi

{
  "v3_use_offset": true,
  "token_hmac_secret_key": "97255635-aae8-44d3-b892-2d98cad09acb",
  "admin_password": "ebb565d1-b15e-496e-845c-d84fcc78900f",
  "admin_secret": "17fb1cf9-c9c2-450d-a6c7-762653f7b1ae",
  "api_key": "750a4155-8f0d-414a-8021-fc18bf19fa54",
  "admin": true,
  "health": true,
  "redis_host": "127.0.0.1",
  "redis_port": "6379",
  "tls": true,
  "tls_cert": "/etc/centrifugo/ssl/fullchain.cer",
  "tls_key": "/etc/centrifugo/ssl/centrifugo.jaranguda.com.key"
}

sesuaikan dengan credential dan domain anda.

Setelah semuanya berjalan dengan normal, kita akan membuat service systemd, untuk memudahkan proses restart dan startnya

cat >/lib/systemd/system/centrifugo.service <<'EOL'
[Unit]
Description=Centrifugo services
After=network.target syslog.target
 
[Service]
User=centrifugo
Group=centrifugo
LimitNOFILE=65555
 
Environment="CONFIG=/etc/centrifugo/config.json"
ExecStartPre=/usr/local/bin/centrifugo checkconfig -c $CONFIG
ExecStart=/usr/local/bin/centrifugo -c $CONFIG
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -SIGTERM $MAINPID
TimeoutStopSec=10
KillMode=control-group
RestartSec=1
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=centrifugo
 
[Install]
WantedBy=multi-user.target
Alias=centrifugo.service
EOL

aktifkan Centrifugo waktu reboot

systemctl enable centrifugo

jalankan Centrifugo

systemctl start centrifugo

Sekarang buka kembali centrifugo di https://DOMAIN:8000

Generate Token Centrifugo

cd /etc/centrifugo
centrifugo gentoken
# output
HMAC SHA-256 JWT for anonymous user with expiration TTL 168h0m0s:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTc0NjYxNTd9.9o715owkOzMnJHQznjKO4y7d4RM2X5HUEJ-Xzk1COAo

Contoh Penggunaan Client

buat file centrifugo-testing.html yang berisi

<html>
    <head>
        <title>Centrifugo - Jaranguda.com</title>
    </head>
    <body>
        <script src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@2.6.4/dist/centrifuge.min.js"></script>
        <script type="text/javascript">
            const centrifuge = new Centrifuge("wss://centrifugo.jaranguda.com:8000/connection/websocket");
            centrifuge.setToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1OTc0NjYxNTd9.9o715owkOzMnJHQznjKO4y7d4RM2X5HUEJ-Xzk1COAo");
 
            centrifuge.on('connect', function(ctx) {
                console.log("connected", ctx);
            });
 
            centrifuge.on('disconnect', function(ctx) {
                console.log("disconnected", ctx);
            });
<img src="https://media.jaranguda.com/2020/08/halaman-dashboard-centrifugo-1024x687.png" alt="halaman dashboard centrifugo" width="1024" height="687" class="alignnone size-large wp-image-17479" />
            centrifuge.connect();
        </script>
    </body>
</html>

Statistik Pengguna Centrifugo

Halaman dashboard admin bisa diakses di https://DOMAIN:8000, login dengan menggunakan admin_password di file /etc/centrifugo/config.json

Perintah Command Line Centrifugo

Ada banyak parameter yang bisa digunakan di centrifugo, daftar lengkapnya dilihat dengan centrifugo --help

Centrifugo – scalable real-time messaging server in language-agnostic way
 
Usage:
   [flags]
   [command]
 
Available Commands:
  checkconfig Check configuration file
  checktoken  Check connection JWT
  genconfig   Generate minimal configuration file to start with
  gentoken    Generate sample connection JWT for user
  help        Help about any command
  version     Centrifugo version information
 
Flags:
  -a, --address string                   interface address to listen on
      --admin                            enable admin web interface
      --admin_external                   enable admin web interface on external port
      --admin_insecure                   use insecure admin mode – no auth required for admin socket
      --api_insecure                     use insecure API mode
      --broker string                    custom broker to use: ex. nats
      --client_insecure                  start in insecure client mode
  -c, --config string                    path to config file (default "config.json")
      --debug                            enable debug endpoints
  -e, --engine string                    engine to use: memory or redis (default "memory")
      --grpc_api                         enable GRPC API server
      --grpc_api_port int                port to bind GRPC API server to (default 10000)
      --grpc_api_tls                     enable TLS for GRPC API server, requires an X509 certificate and a key file
      --grpc_api_tls_cert string         path to an X509 certificate file for GRPC API server
      --grpc_api_tls_disable             disable general TLS for GRPC API server
      --grpc_api_tls_key string          path to an X509 certificate key for GRPC API server
      --health                           enable health check endpoint
  -h, --help                             help for this command
      --internal_address string          custom interface address to listen on for internal endpoints
      --internal_port string             custom port for internal endpoints
      --log_file string                  optional log file - if not specified logs go to STDOUT
      --log_level string                 set the log level: debug, info, error, fatal or none (default "info")
  -n, --name string                      unique node name
      --nats_url string                  Nats connection URL in format nats://user:pass@localhost:4222 (Nats broker)
      --pid_file string                  optional path to create PID file
  -p, --port string                      port to bind HTTP server to (default "8000")
      --prometheus                       enable Prometheus metrics endpoint
      --redis_db int                     Redis database (Redis engine)
      --redis_host string                Redis host (Redis engine) (default "127.0.0.1")
      --redis_master_name string         name of Redis master Sentinel monitors (Redis engine)
      --redis_password string            Redis auth password (Redis engine)
      --redis_port string                Redis port (Redis engine) (default "6379")
      --redis_sentinel_password string   Redis Sentinel auth password (Redis engine)
      --redis_sentinels string           comma-separated list of Sentinel addresses (Redis engine)
      --redis_tls                        enable Redis TLS connection
      --redis_tls_skip_verify            disable Redis TLS host verification
      --redis_url string                 Redis connection URL in format redis://:password@hostname:port/db (Redis engine)
      --tls                              enable TLS, requires an X509 certificate and a key file
      --tls_cert string                  path to an X509 certificate file
      --tls_external                     enable TLS only for external endpoints
      --tls_key string                   path to an X509 certificate key
 
Use " [command] --help" for more information about a command.

Leave a comment

Your email address will not be published. Required fields are marked *