Управление подписками
Настройте подписки на резервном сервере и управляйте ими, чтобы получать и применять изменения из публикации.
«Управление подписками» — бесплатный урок Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit. Это урок 3 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Advanced PostgreSQL: Indexing, Partitioning, Replication, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
What is a Logical Subscription?
In PostgreSQL's logical replication, a subscription is the receiving end. It's configured on a subscriber server to connect to a publisher server and pull data changes from a specific publication.
Think of it as subscribing to a newspaper. The publisher creates the newspaper (publication), and you (the subscriber) sign up to receive it.
The Subscriber Server Role
The server where you create a subscription becomes the subscriber. This server will connect to the publisher, receive the changes (inserts, updates, deletes, truncates), and apply them to its local tables.
It's crucial that the tables on the subscriber have the same structure as the published tables on the master for replication to work correctly.
Creating a New Subscription
To start receiving data, you use the CREATE SUBSCRIPTION command. You need to specify the connection details to the publisher and the name of the publication you want to subscribe to.
This command is run on the subscriber database.
CREATE SUBSCRIPTION my_app_sub
CONNECTION 'dbname=source_db host=192.168.0.10 user=repl_user password=securepass'
PUBLICATION app_data_pub;Essential Subscription Options
When creating a subscription, several options control its behavior:
COPY_DATA: Iftrue(default), existing data from the published tables is copied.ENABLED: Iftrue(default), replication starts immediately.CREATE_SLOT: Iftrue(default), a replication slot is created on the publisher.SLOT_NAME: You can specify an existing slot name instead of creating a new one.
Full Subscription Example
Let's create a subscription named sales_replica. It connects to a publisher at 10.0.0.5, user repl_admin, for the publication sales_publication.
We explicitly ask to copy existing data and enable it right away.
-- Execute this on the subscriber database
CREATE SUBSCRIPTION sales_replica
CONNECTION 'dbname=sales_db host=10.0.0.5 user=repl_admin password=mysecret'
PUBLICATION sales_publication
WITH (copy_data = true, create_slot = true, enabled = true);Monitoring Subscription Status
After creating a subscription, you'll want to ensure it's running correctly. PostgreSQL provides the pg_stat_subscription view for this.
It shows details like connection info, enabled status, and the current state of replication.
-- On the subscriber server
SELECT
subname,
subenabled,
substate,
subslotname,
subconninfo
FROM pg_stat_subscription;Enabling and Disabling Subscriptions
You might need to temporarily pause replication, for example, during maintenance or schema changes. You can enable or disable a subscription using ALTER SUBSCRIPTION.
DISABLE: Stops the replication process.ENABLE: Resumes the replication process.
-- Temporarily stop replication for 'sales_replica'
ALTER SUBSCRIPTION sales_replica DISABLE;
-- Resume replication
ALTER SUBSCRIPTION sales_replica ENABLE;Refreshing Publication List
If the publisher adds new tables to a publication, the subscriber won't automatically start replicating them. You need to tell the subscriber to refresh its understanding of the publication.
The REFRESH PUBLICATION command updates the subscription's table list.
-- Update 'sales_replica' to include any newly added tables
ALTER SUBSCRIPTION sales_replica REFRESH PUBLICATION;Dropping a Subscription
When a subscription is no longer needed, you can drop it. This command is executed on the subscriber server. By default, it also attempts to drop the associated replication slot on the publisher.
Ensure the subscription is disabled before dropping it to prevent errors.
-- First, disable the subscription if it's enabled
ALTER SUBSCRIPTION sales_replica DISABLE;
-- Then, drop the subscription
DROP SUBSCRIPTION sales_replica;Subscription Management Check
You have a subscription named user_data_sub that is actively replicating data. You need to perform some schema changes on the subscriber and want to temporarily stop the data flow without removing the subscription entirely.
Recap: Managing Subscriptions
In this lesson, you learned how to manage subscriptions in PostgreSQL logical replication. You can create new subscriptions, monitor their status, enable/disable them for maintenance, refresh their publication list, and finally drop them when no longer needed.
Mastering these commands is key to maintaining a robust and flexible logical replication setup.
Часто задаваемые вопросы
Урок «Управление подписками» бесплатный?
Да — полный текст урока «Управление подписками» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Advanced PostgreSQL: Indexing, Partitioning, Replication, подпишись на CoddyKit PRO. Курс Advanced PostgreSQL: Indexing, Partitioning, Replication содержит 4 уроков всего.
Чему я научусь в уроке «Управление подписками»?
Настройте подписки на резервном сервере и управляйте ими, чтобы получать и применять изменения из публикации. Ты практикуешь Advanced PostgreSQL: Indexing, Partitioning, Replication с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Advanced PostgreSQL: Indexing, Partitioning, Replication?
Предыдущий опыт не требуется. Advanced PostgreSQL: Indexing, Partitioning, Replication на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 3 из 4.
Сколько времени занимает урок «Управление подписками»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Advanced PostgreSQL: Indexing, Partitioning, Replication?
Да. Каждый урок Advanced PostgreSQL: Indexing, Partitioning, Replication включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Основы логической репликации
- Настройка публикаций
- Управление подписками
- Разрешение конфликтов при логической репликации