Tracciare la presenza e lo stato online
Costruisca un sistema di presenza in tempo reale che mostri chi è online, trasmettendo gli eventi di connessione e disconnessione e rendendo visibile lo stato aggiornato degli utenti.
Tracciare la presenza e lo stato online è una lezione WebSockets & Real-Time Systems with Spring gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento WebSockets & Real-Time Systems with Spring, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
What Is Presence?
Presence is knowing who is currently online: the green dots in chat apps, the live cursors in collaborative editors, the active-now lists. It is one of the most requested real-time features.
Presence Is About Lifecycle Events
The core insight: presence is derived from connection lifecycle. When a session opens, mark the user online; when it closes, mark them offline, then broadcast the change.
Listening to Connect Events
Spring publishes a SessionConnectedEvent when a STOMP session is established. Use it to record the user as online.
@EventListener
public void onConnect(SessionConnectedEvent e) {
String user = e.getUser().getName();
presence.markOnline(user);
broadcast(user, "ONLINE");
}Listening to Disconnect Events
A matching SessionDisconnectEvent fires on close. Mark the user offline and broadcast it.
@EventListener
public void onDisconnect(SessionDisconnectEvent e) {
String user = userFor(e.getSessionId());
presence.markOffline(user);
broadcast(user, "OFFLINE");
}Storing Presence State
For a single server a concurrent map works. For a cluster, store presence in Redis so every node sees the same online set.
redis.opsForSet().add("online:users", username);
redis.opsForValue().set("presence:" + username, "ONLINE", Duration.ofMinutes(2));Broadcasting Status Changes
Push each change to a presence topic so every interested client updates its UI live.
messagingTemplate.convertAndSend("/topic/presence",
new PresenceEvent(username, status));Multiple Tabs and Devices
A user with two tabs has two sessions. Reference-count them: only mark offline when the last session closes, or you will flicker the status.
Handling Ungraceful Disconnects
A crash may not send a clean close. Pair presence with heartbeats and a TTL: if no heartbeat arrives before the key expires, treat the user as offline.
Last-Seen Timestamps
Beyond online/offline, record a last-seen time on disconnect. The UI can then show "active 5 minutes ago" for offline users.
redis.opsForValue().set("lastseen:" + username, Instant.now().toString());Sending the Initial Snapshot
When a client first connects it needs the current online list, not just future changes. Send a snapshot on subscription, then stream deltas.
@SubscribeMapping("/presence.init")
public Set<String> initial() {
return presence.onlineUsers();
}Privacy Considerations
Presence can leak behavior patterns. Offer an invisible mode and respect it server-side, so a user who opts out is never broadcast as online.
Quick Check
Test your presence knowledge.
Recap
You built presence:
- Presence derives from connect/disconnect lifecycle events
- Use
SessionConnectedEvent/SessionDisconnectEventand broadcast changes - Store shared state in Redis for clustering; reference-count multiple sessions
- Pair with heartbeats and TTLs to catch ungraceful disconnects
- Send an initial snapshot, track last-seen, and honor invisible mode
Domande Frequenti
La lezione «Tracciare la presenza e lo stato online» è gratuita?
Sì — il testo completo di «Tracciare la presenza e lo stato online» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso WebSockets & Real-Time Systems with Spring, passa a CoddyKit PRO. Il corso WebSockets & Real-Time Systems with Spring include 4 lezioni in totale.
Cosa imparerò in «Tracciare la presenza e lo stato online»?
Costruisca un sistema di presenza in tempo reale che mostri chi è online, trasmettendo gli eventi di connessione e disconnessione e rendendo visibile lo stato aggiornato degli utenti. Eserciti WebSockets & Real-Time Systems with Spring con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare WebSockets & Real-Time Systems with Spring?
Non è richiesta alcuna esperienza precedente. WebSockets & Real-Time Systems with Spring su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Tracciare la presenza e lo stato online»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione WebSockets & Real-Time Systems with Spring?
Sì. Ogni lezione WebSockets & Real-Time Systems with Spring include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Server-Sent Events (SSE) vs. WebSockets
- Architetture per il push dei dati in tempo reale
- Implementazione delle notifiche utente
- Tracciare la presenza e lo stato online