Simplifica la Transferencia de MySQL a PostgreSQL

Guía completa para lograr la sincronización de datos de MySQL a PostgreSQL con Apache SeaTunnel 2.3.9. Explicamos desde la configuración del entorno hasta la validación en producción, incluyendo replicación, permisos, configuración de clúster y optimización del rendimiento.

21 mar 2025 • 3 min read • Q2BSTUDIO Team

Empresa-Software-Apps

Este artículo proporciona una guía detallada sobre cómo lograr una sincronización completa de datos de MySQL a PostgreSQL utilizando Apache SeaTunnel 2.3.9. Se cubre todo el proceso, desde la configuración del entorno hasta la validación en producción.

Requisitos de versión:

  • MySQL: MySQL 8.3
  • PostgreSQL: PostgreSQL 13.2
  • Apache SeaTunnel: Apache-SeaTunnel-2.3.9

Verificación de versiones:

Ejecuta el siguiente comando SQL para verificar la versión:

  
select version();  

Habilitación de replicación maestro-esclavo:

  
show variables where variable_name in ('log_bin', 'binlog_format', 'binlog_row_image', 'gtid_mode', 'enforce_gtid_consistency');  

Para la sincronización de datos en MySQL CDC, SeaTunnel necesita leer el binlog y actuar como un nodo esclavo en el clúster.

  
SET GLOBAL gtid_mode=OFF_PERMISSIVE;  
SET GLOBAL gtid_mode=ON_PERMISSIVE;  
SET GLOBAL enforce_gtid_consistency=ON;  
SET GLOBAL gtid_mode=ON;  

Concesión de permisos de usuario:

Se requiere un usuario con privilegios de replicación:

  
CREATE USER 'test'@'%' IDENTIFIED BY 'password';  
GRANT SELECT, RELOAD, SHOW DATABASES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO 'test';  
FLUSH PRIVILEGES;  

Configuración del clúster de SeaTunnel:

Por defecto, SeaTunnel genera logs en un solo archivo. Para producción, es recomendable separar los registros por tarea:

  
rootLogger.appenderRef.file.ref = routingAppender  

En entornos de producción, se recomienda instalar SeaTunnel en el directorio /opt y configurar la variable de entorno SEATUNNEL_HOME:

  
ln -s /opt/apache-seatunnel-2.3.9 /opt/seatunnel  
export SEATUNNEL_HOME=/opt/seatunnel  

Configuración del trabajo en SeaTunnel:

  
env {  
  job.mode = 'STREAMING'  
  job.name = 'DEMO'  
  parallelism = 3  
  checkpoint.interval = 30000  
  checkpoint.timeout = 30000  
  job.retry.times = 3  
  job.retry.interval.seconds = 3  
}  

Configurar un nombre de tarea es esencial para administrar trabajos en producción. Además, se establece un nivel de paralelismo de 3, pero se puede ajustar según el tamaño del clúster.

Configuración del origen de datos (MySQL CDC):

  
source {  
  MySQL-CDC {  
    base-url = 'jdbc:mysql://192.168.8.101:3306/test?serverTimezone=Asia/Shanghai'  
    username = 'test'  
    password = '123456'  
    database-names = ['test']  
    table-pattern = 'test\.test_.*'  
    startup.mode = 'initial'  
    snapshot.split.size = '8096'  
    snapshot.fetch.size = '1024'  
    server-id = '6500-8500'  
    exactly_once = false  
    schema-changes.enabled = true  
  }  
}  

Se configura la sincronización tanto para datos históricos como incrementales. Se recomienda la habilitación de la evolución de esquemas para manejar cambios en la estructura de las tablas.

Configuración del destino (PostgreSQL):

  
sink {  
  jdbc {  
    url = 'jdbc:postgresql://192.168.8.101:5432/test'  
    driver = 'org.postgresql.Driver'  
    user = 'postgres'  
    password = '123456'  
    generate_sink_sql = true  
    database = 'test'  
    table = '${database_name}.${table_name}'  
    schema_save_mode = 'CREATE_SCHEMA_WHEN_NOT_EXIST'  
    data_save_mode = 'APPEND_DATA'  
  }  
}  

La opción generate_sink_sql genera automáticamente las sentencias de inserción y actualización. También se configura el modo de almacenamiento del esquema para crear automáticamente las tablas si no existen.

Envío y monitoreo de tareas:

  
./bin/start-seatunnel.sh --config /path/to/config.yaml --async  

El flag --async permite que la tarea se ejecute en segundo plano mientras se monitorea a través de la interfaz de SeaTunnel.

Demostración de sincronización de datos:

Se probaron inserciones, actualizaciones y eliminaciones en MySQL, y los cambios fueron replicados exitosamente en PostgreSQL.

Sobre Apache SeaTunnel:

  • Soporta cientos de fuentes de datos.
  • Manejo de sincronización completa, incremental y en tiempo real.
  • Monitoreo eficaz para evitar pérdida o duplicación de datos.

En Q2BSTUDIO, una empresa especializada en desarrollo y servicios tecnológicos, ayudamos a implementar soluciones de sincronización de datos para garantizar la integridad y eficiencia en el manejo de datos en entornos empresariales. Con experiencia en la integración de Apache SeaTunnel, proporcionamos asesoría y desarrollo de estrategias personalizadas para optimizar la transferencia de datos entre diversas plataformas, asegurando rendimiento y escalabilidad.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.