Canais versus notificações de espaço de chaves
Entenda a diferença entre canais explícitos de Pub/Sub e notificações de espaço de chaves do Redis, além de saber quando usar cada um.
Canais versus notificações de espaço de chaves é uma aula grátis de Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Redis Caching & Messaging (Pub/Sub, Streams), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
Two Ways to Get Notified
So far you have published to explicit channels with PUBLISH. Redis also offers keyspace notifications, which automatically emit events when keys change. Both deliver messages to subscribers, but the source differs.
Recap: Explicit Channels
With explicit channels, your application decides what to publish and when. The channel name is arbitrary text.
PUBLISH news.sports "Match ended 2-1"
SUBSCRIBE news.sportsWhat Are Keyspace Notifications?
Keyspace notifications let Redis itself publish an event whenever a key is modified, expired, or evicted. You subscribe to special channels to observe data changes without your app having to publish anything.
Enabling Notifications
They are off by default. Enable them with the notify-keyspace-events config flag, where letters select event classes.
Kkeyspace eventsEkeyevent eventsAall command/event typesxexpired,ggeneric,$string
CONFIG SET notify-keyspace-events KEAKeyspace vs Keyevent
There are two channel families:
- Keyspace:
__keyspace@0__:mykeytells you which event happened to a key - Keyevent:
__keyevent@0__:deltells you which keys had a given event
The @0 is the database number.
PSUBSCRIBE __keyspace@0__:*
PSUBSCRIBE __keyevent@0__:expiredSubscribing to Expirations
A common use case is reacting when a key expires, for example to clean up a session. Enable Ex and subscribe to the expired keyevent channel.
CONFIG SET notify-keyspace-events Ex
SUBSCRIBE __keyevent@0__:expiredA Practical Flow
Set a session key with a TTL. When it expires, Redis publishes to the expired channel, and your worker reacts.
SET session:abc "data" EX 30
# 30s later, subscriber receives:
# __keyevent@0__:expired -> session:abcDelivery Caveats
Keyspace notifications use Pub/Sub, so they are fire-and-forget. If no client is subscribed when the event fires, the message is lost. They are also not guaranteed for keys that expire while idle until a read or the background expiry cycle touches them.
When to Use Each
Use explicit channels when your app controls the event semantics (chat, notifications, custom events). Use keyspace notifications when you want to react to data mutations you do not directly control, like cache invalidation or expiry cleanup.
Performance Note
Enabling A (all events) on a busy server generates a high volume of messages and adds overhead. Subscribe only to the specific event classes you need.
CONFIG SET notify-keyspace-events EgxSummary So Far
Explicit channels are app-driven; keyspace notifications are Redis-driven. Both ride on the same lightweight Pub/Sub transport, so neither persists messages.
Quick Check
Pick the correct statement about keyspace notifications.
Recap
You compared explicit Pub/Sub channels with keyspace notifications, learned how to enable notifications via notify-keyspace-events, the keyspace vs keyevent channel families, and the fire-and-forget delivery caveats. Reach for keyspace notifications to react to data changes without publishing them yourself.
Perguntas Frequentes
A aula “Canais versus notificações de espaço de chaves” é grátis?
Sim — o texto completo de “Canais versus notificações de espaço de chaves” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Redis Caching & Messaging (Pub/Sub, Streams), atualize para CoddyKit PRO. O curso de Redis Caching & Messaging (Pub/Sub, Streams) inclui 4 aulas no total.
O que vou aprender em “Canais versus notificações de espaço de chaves”?
Entenda a diferença entre canais explícitos de Pub/Sub e notificações de espaço de chaves do Redis, além de saber quando usar cada um. Você pratica Redis Caching & Messaging (Pub/Sub, Streams) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Redis Caching & Messaging (Pub/Sub, Streams)?
Nenhuma experiência prévia é necessária. Redis Caching & Messaging (Pub/Sub, Streams) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Canais versus notificações de espaço de chaves”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Redis Caching & Messaging (Pub/Sub, Streams)?
Sim. Cada aula de Redis Caching & Messaging (Pub/Sub, Streams) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- Introdução a publicação e assinatura
- Mecânica de publicação e assinatura no Redis
- Transmissão de mensagens simples
- Canais versus notificações de espaço de chaves