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

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Giới Thiệu

Trong bài viết này, chúng ta sẽ tạo một real-time chat application đơn giản cho phép user join chat group và communicate real-time.

Tận dụng Ably cho real-time messaging cross-user low latency, Upstash Redis lưu trữ tin nhắn persistently, và Node.js xây ứng dụng.

Ably

Ably là real-time experience platform cho two-way communication giữa users.

Đối với chat app này, dùng Pub/Sub channels của Ably: user send message bằng "publish" message đến Ably channel, user receive message bằng "subscribe".

Ably cung cấp Pub/Sub channels bằng cách thêm abstract layer trên Web Sockets với features bổ sung:

  • Presence của subscribers
  • Authentication
  • Heartbeat mechanism
  • Queues
  • Deliver messages theo thứ tự published
  • Integrations invoke functions bởi event trên Ably
  • Stream messages/presence/metadata đến Kafka

Tạo ứng dụng trên Ably: tạo tài khoản, chọn “Live Chat”.

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Chưa cần làm gì thêm. Sẽ quay lại dashboard lấy API key sau.

Upstash Redis

Dùng Upstash Redis lưu chat messages persistently — cho phép user retrieve chat history khi join.

Upstash Redis cũng lưu chat messages sebagai sorted list — giúp gửi message từ DB đến client không cần re-sort.

Tạo Upstash Redis database: Upstash Console, login, tạo Redis database.

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Infrastructure ready. Chuyển sang architecture chat app.

Kiến Trúc Chat App

Thiết kế đơn giản:

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Demo project chỉ tạo 1 Ably channel. Client publish message đến channel. Client khác receive ngay qua subscription.

Ngoài real-time messaging giữa client, cần store message Upstash Redis. Ably channel có thêm 1 subscriber — server. Server receive message từ client, gửi Upstash Redis lưu.

Cuối cùng, dùng chat history trong Upstash Redis qua server. Tạo endpoint "/history" server-side trả chat history từ Redis. Client retrieve history khi load app bằng cách call endpoint này.

Đây là simple chat app demo. Có thể modify/extend dùng features khác của Ably đã nêu.

Client Side

Tạo basic chat UI. File index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="index.css">
  <title>Chat App</title>
</head>
<body>
  <div class="container">
    <p class="msg">Messages:</p>
    <div id="messages" class="messages"></div>
    <form id="msgForm" class="msgForm">
      <input type="text" placeholder="Send message" class="input" id="inputBox" />
      <input type="submit" class="btn" value="Send">
    </form>
  </div>
  <script src="https://cdn.ably.io/lib/ably.min-1.js"></script>
  <script src="app.js"></script>
</body>
</html>

Browser hiển thị: input field type message, submit button send, message boxes display previous messages.

File app.js — JavaScript chạy trên web page.

Tạo Ably channel. Quay lại Ably dashboard, tạo API key mới dưới “API Keys”. Chọn “Publish” và “Subscribe” capabilities.

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Tạo Ably client trong JavaScript dùng Key từ dashboard:

const ably = new Ably.Realtime('<Ably API Key>');

Cảnh báo: Đưa API key cho client KHÔNG AN TOÀN. Ably có mechanism “TokenRequest”. Vì demo, đưa API key trực tiếp. Xem Ably token docs cho client authentication.

Lấy Ably channel client communicate:

const channel = ably.channels.get('chat');

Không cần tạo channel — channel tạo khi ai đó publish.

Lấy username từ user (simple, auth không phải focus):

let name = window.prompt("Please enter your name.", "Anonymous");

Implement gửi message:

const form = document.getElementById('msgForm');
form.addEventListener('submit', (event) => {
  event.preventDefault();
  const message = document.getElementById('inputBox').value;
  if (message.trim() !== '') {
    const messageData = { name: name, message: message }
    channel.publish('message', messageData);
    document.getElementById('inputBox').value = '';
  }
});

Gửi message đơn giản: tạo object chứa username và message, publish đến Ably channel.

Enable receive message: subscribe channel, add message box chứa username và message:

channel.subscribe('message', (message) => {
  console.log("Client received: ", message);
  displayMessage(message.data);
});

function displayMessage(message) {
  const incomingName = message.name;
  const incomingMessage = message.message;
  const messageElement = document.createElement('div');
  const messageValue = document.createElement('div');
  const messageWriter = document.createElement('div');
  if(incomingName !== name){
    messageElement.classList.add('msgSent');
  } else {
    messageElement.classList.add('msgReceived');
  }
  messageWriter.classList.add('msgWriter');
  messageValue.classList.add('msgValue');
  messageWriter.textContent = incomingName;
  messageValue.textContent = incomingMessage;
  messageElement.appendChild(messageWriter);
  messageElement.appendChild(messageValue);
  const list = document.getElementById('messages');
  list.appendChild(messageElement);
}

Retrieve chat history khi page load lần đầu:

document.addEventListener("DOMContentLoaded", function() {
  fetchChatHistory();
});

function fetchChatHistory() {
  fetch('/history')
    .then((response) => {
      if (!response.ok) throw new Error('Failed to fetch chat history');
      return response.json();
    })
    .then((data) => {
      const history = data.history;
      console.log(history);
      if (history && history.length > 0) {
        history.forEach((message) => {
          displayMessage(JSON.parse(message));
        });
      }
    })
    .catch((error) => {
      console.error('Error fetching chat history:', error);
    });
}

Server Side

Server demo: subscribe Ably channel, push Upstash Redis, return chat history từ Redis khi client request.

Cấu hình server trong app.js:

var express = require('express');
var path = require('path');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));
var router = express.Router();
router.get('/', function(req, res, next) {
  res.render('index', { title: 'ChatApp' });
});
app.use('/', router);
module.exports = app;

Tạo server trong server.js, subscribe Ably channel, connect Upstash Redis:

var app = require('../app');
var http = require('http');
const redis = require('redis');
const Ably = require('ably');
const port = process.env.PORT || '3000';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);

const redisClient = redis.createClient({ url: "<Upstash Redis Endpoint>" });
redisClient.on("error", function(err) { throw err; });
redisClient.connect().then(r => { console.log("Connected to Redis.") })

const ably = new Ably.Realtime({ key: '<Ably API Key>', });
const channel = ably.channels.get('chat');

Push incoming messages đến Upstash Redis qua Ably subscription:

channel.subscribe('message', async (message) => {
  const convertedMessage = JSON.stringify(message.data);
  console.log('Received message:', convertedMessage);
  await redisClient.LPUSH("AblyChatList", convertedMessage);
});

Implement endpoint “/history” retrieve chat history từ Upstash Redis trả client:

app.get('/history', async (req, res) => {
  const messages = await redisClient.LRANGE("AblyChatList", 0, -1);
  messages.reverse();
  console.log("history api: ", messages);
  res.json({ history: messages });
});

Chạy App

Vào directory chứa server.js chạy:

node server.js

Mở localhost:3000 browser. Hỏi username trước.

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Nhập username, mở chat.

Gửi message từ tab 1, mở localhost:3000 tab 2 với username khác — thấy message từ tab 1.

Xây Dựng Real-Time Chat App Với Ably, Upstash Redis & Node.js

Nhờ Upstash Redis, retrieve chat history mỗi lần mở chat app.

Kết Luận

Ably cung cấp nhiều features tăng cường real-time communication. Real-time world mạnh mẽ của Ably áp dụng cho hàng tá use cases.

Bài viết dùng Ably Pub/Sub channels xây real-time chat app, lưu message Upstash Redis. Hai tool này làm app dễ build và fast.

Vì project demo Upstash Redis và Ably, scope rất simple. Nếu quan tâm, có thể build robust, scalable, secure real-time apps tận dụng features Ably và Upstash Redis.