0Pricing
Redis Caching & Messaging (Pub/Sub, Streams) · Ders

Gerçek Zamanlı Sohbet Tasarlama

Mesaj iletimi için Yayınla/Abone Ol kullanımını gösteren temel bir gerçek zamanlı sohbet uygulaması uygulayın.

Gerçek Zamanlı Sohbet Tasarlama, CoddyKit'te ücretsiz bir Redis Caching & Messaging (Pub/Sub, Streams) dersidir. Bu, 4 dersinin 2. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Redis Caching & Messaging (Pub/Sub, Streams) öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Redis Caching & Messaging (Pub/Sub, Streams) kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

Real-time Chat with Pub/Sub

Imagine building a chat application where messages appear instantly! This is where Redis Pub/Sub shines. It's perfect for real-time communication without constant 'checking for new messages'.

In this lesson, you'll learn how to design a basic chat system using Redis Publish/Subscribe, turning chat rooms into channels and messages into published events.

Chat Rooms as Redis Channels

The core idea for a chat application with Pub/Sub is simple: each chat room corresponds to a unique Redis Channel.

  • When a user wants to join a chat room (e.g., 'general' or 'support'), their client application will subscribe to the corresponding Redis channel.
  • When a user sends a message in that room, their client will publish the message to that specific channel.

Subscribing to Join a Room

To 'join' a chat room, a client needs to start listening for messages on its channel. This is done by subscribing. Once subscribed, the client will receive all messages published to that channel.

Below is a simplified Java example using a Redis client library (like Jedis) to subscribe to a channel named chat:general.

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class ChatSubscriber {
  public static void main(String[] args) {
    try (Jedis jedis = new Jedis("localhost")) {
      System.out.println("Subscribing to chat:general...");
      jedis.subscribe(new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
          System.out.println("Received on " + channel + ": " + message);
        }
      }, "chat:general");
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Publishing to Send Messages

When a user types a message and hits 'send', their client application will publish that message to the channel corresponding to the current chat room. All clients currently subscribed to that channel will immediately receive the message.

This Java example shows how a client would publish a message to the chat:general channel.

import redis.clients.jedis.Jedis;

public class ChatPublisher {
  public static void main(String[] args) {
    try (Jedis jedis = new Jedis("localhost")) {
      String message = "Hello, everyone!";
      jedis.publish("chat:general", message);
      System.out.println("Published: '" + message + "'");
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Demo: User A Listens

Let's see this in action! Run this program in one terminal. It simulates User A joining the chat:general room and waiting for messages. It will block and print any message it receives.

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPubSub;

public class UserA {
  public static void main(String[] args) {
    try (Jedis jedis = new Jedis("localhost")) {
      System.out.println("User A is listening on chat:general...");
      jedis.subscribe(new JedisPubSub() {
        @Override
        public void onMessage(String channel, String message) {
          System.out.println("User A received: " + message);
        }
      }, "chat:general");
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Demo: User B Sends

Now, open a separate terminal and run this program. It simulates User B sending a message to the chat:general room. Watch User A's terminal – it should instantly receive User B's message!

import redis.clients.jedis.Jedis;

public class UserB {
  public static void main(String[] args) {
    try (Jedis jedis = new Jedis("localhost")) {
      String message = "Hey User A, are you there?";
      jedis.publish("chat:general", message);
      System.out.println("User B published: '" + message + "'");
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Designing Your Chat Message

A simple string message isn't usually enough for a chat application. You'll want to include more context. A common approach is to serialize chat message data into a format like JSON before publishing it.

Consider including:

  • sender: The username or ID of who sent the message.
  • timestamp: When the message was sent (for ordering).
  • text: The actual content of the message.
  • roomId: (Optional) The channel/room ID, useful for client-side processing.

Handling Multiple Chat Rooms

To support many different chat rooms (e.g., 'general', 'private:alice-bob', 'developers'), you simply use different channel names.

  • Each room gets a unique channel name (e.g., chat:general, chat:support).
  • Clients subscribe only to the channels of the rooms they are active in.
  • When a user switches rooms, their client unsubscribes from the old channel and subscribes to the new one.

Pub/Sub's Non-Persistent Nature

It's crucial to remember that Redis Pub/Sub is a fire-and-forget system. Messages are delivered to all currently active subscribers and then disappear.

  • If a user is offline or not subscribed when a message is published, they will not receive that message when they come back online.
  • For persistent chat history or messages to offline users, you would need to combine Pub/Sub with other Redis data structures (like Lists or Streams) or a separate database.

Chat Design Quiz

You're building a chat app with Redis Pub/Sub. Users join rooms by subscribing to channels. If User A is subscribed to chat:tech and User B publishes a message to chat:random, what happens?

Recap: Real-time Chat Design

You've learned the basics of designing a real-time chat application using Redis Pub/Sub:

  • Each chat room maps to a unique Redis channel.
  • Users subscribe to a channel to join a room and receive messages.
  • Users publish messages to a channel to send them to all subscribers.
  • Messages should be structured (e.g., JSON) to include sender, timestamp, and content.
  • Remember that Pub/Sub is non-persistent; messages are gone once delivered.

This foundation allows for highly responsive chat experiences!

Sıkça Sorulan Sorular

“Gerçek Zamanlı Sohbet Tasarlama” dersi ücretsiz mi?

Evet — “Gerçek Zamanlı Sohbet Tasarlama” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Redis Caching & Messaging (Pub/Sub, Streams) kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Redis Caching & Messaging (Pub/Sub, Streams) kursu toplamda 4 dersten oluşur.

“Gerçek Zamanlı Sohbet Tasarlama” dersinde ne öğreneceğim?

Mesaj iletimi için Yayınla/Abone Ol kullanımını gösteren temel bir gerçek zamanlı sohbet uygulaması uygulayın. Redis Caching & Messaging (Pub/Sub, Streams) ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Redis Caching & Messaging (Pub/Sub, Streams) öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Redis Caching & Messaging (Pub/Sub, Streams), başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 2. dersidir.

“Gerçek Zamanlı Sohbet Tasarlama” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Redis Caching & Messaging (Pub/Sub, Streams) dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Redis Caching & Messaging (Pub/Sub, Streams) dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Kalıba Dayalı Abonelikler
  2. Gerçek Zamanlı Sohbet Tasarlama
  3. Olay Odaklı Mimari
  4. Varlık ve Çevrimiçi Durum İzleme
← Redis Caching & Messaging (Pub/Sub, Streams) Sayfasına Dön