Java는 MySQLBinListener를 사용하여 MySQL 데이터베이스 변경 사항의 실시간 모니터링을 구현합니다.

목차

1. 필요한 클래스와 인터페이스 내보내기

2. MySQLBinlogListener 클래스 정의

3. 비공개 방법, 재연결 타이머 시작

4. 완전한 코드


 

MySQL 데이터베이스의 실시간 변경 사항에 대한 리스너를 작성합니다.

이 리스너를 작성하는 이유: MySQL 데이터베이스의 변경 이벤트를 실시간으로 모니터링하고 이에 응답하기 위해

  1. 실시간 데이터 동기화: MySQL Binlog를 모니터링하면 삽입, 업데이트, 삭제 등의 데이터베이스 변경 작업을 캡처하여 데이터 변경 사항을 실시간으로 얻을 수 있습니다. 이는 실시간 분석, 데이터 동기화 등과 같이 시기적절한 데이터 동기화가 필요한 애플리케이션 시나리오에 매우 중요합니다.
  2. 데이터베이스 모니터링 및 감사: 데이터베이스 변경 이벤트를 모니터링하여 데이터베이스에 대한 실시간 모니터링 및 감사가 가능합니다. 데이터베이스의 모든 작업을 캡처하고 기록하여 데이터베이스의 변경 사항을 이해할 수 있으며, 이를 통해 문제 해결 및 보안 감사도 용이해집니다.
  3. 데이터 변경이 비즈니스 로직을 트리거함: 데이터베이스의 데이터가 변경되면 해당 비즈니스 로직이 리스너를 통해 트리거될 수 있습니다. 예를 들어 테이블이 변경되면 알림을 보내거나, 다른 서비스를 호출하거나, 데이터 처리 및 기타 작업을 수행할 수 있습니다.
  4. 데이터 캐싱 및 업데이트: 데이터베이스 변경 이벤트를 수신하여 애플리케이션에 캐시된 데이터를 적시에 업데이트하여 애플리케이션의 성능과 응답 속도를 향상시킬 수 있습니다. 데이터베이스 데이터가 변경되면 리스너를 통해 캐시를 자동으로 새로 고쳐 애플리케이션에서 사용하는 데이터가 최신인지 확인할 수 있습니다.

간단히 말해서, 이러한 리스너를 작성하면 실시간 데이터 동기화, 데이터베이스 모니터링 및 감사, 비즈니스 로직 트리거링, 데이터 캐시 업데이트 및 이기종 데이터 통합과 같은 여러 이점을 제공할 수 있습니다.

그러면 다음과 같은 함수 작성을 시작해 보겠습니다.

1. 필요한 클래스와 인터페이스 내보내기

import com.github.shyiko.mysql.binlog.BinaryLogClient;
import com.github.shyiko.mysql.binlog.event.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

다음으로 Spring 구성 요소 태그를 사용합니다.

@요소

2.  MySQLBinlogListener클래스 정의

공개 클래스 MySQLBinlogListener {

재접속 간격이 정의되었음을 나타내는 상수를 정의하며, 단위는 밀리초로 설정할 수 있다.

private static final int RECONNECT_INTERVAL = 10000;

 주기적으로 MySQL 서버에 다시 연결을 시도하도록 예약된 작업을 정의합니다.

private static Timer reconnectTimer;

MySQL 서버에 연결하기 위한 BinaryLogClient 객체 정의

private static BinaryLogClient client;

종속성 주입을 위한 ApplicationContext 객체 정의

@Autowired
private static ApplicationContext applicationContext;

startMySQLBinlogListenerMySQL Binlog 이벤트 수신을 시작하는 메서드를 호출하는 프로그램의 입력 메서드를 편집합니다.

public void main(String[] args) {
    startMySQLBinlogListener();
}

startMySQLBinlogListenerMySQL Binlog 리스너를 시작하는 데 사용되는 방법은 다음과 같습니다.

public static void startMySQLBinlogListener() {

BinaryLogClient 객체를 생성하고 MySQL 서버의 호스트 이름, 포트 번호, 데이터베이스 이름, 사용자 이름 및 비밀번호를 지정합니다.

client = new BinaryLogClient("127.0.0.1",3306, "你的数据库表","root", "密码");

연결 유지, 하트비트 패킷 전송 간격 및 하트비트 패킷 연결 시간 초과를 포함하여 BinaryLogClient 개체의 일부 속성을 설정합니다.

client.setKeepAlive(true);
client.setKeepAliveInterval(60 * 1000);
client.setKeepAliveConnectTimeout(5 * 1000);

다양한 유형의 이벤트에 응답하려면 이벤트 리스너를 등록하세요. 여기서는 TableMapEventData 유형의 이벤트를 처리하고 테이블 이름을 기반으로 WebSocket 메시지를 전송하며, UpdateRowsEventData, WriteRowsEventData 및 DeleteRowsEventData 유형의 이벤트에 대한 로그를 출력합니다.

client.registerEventListener(event -> {
    try {
        EventData data = event.getData();
        if (data instanceof TableMapEventData) {
            TableMapEventData tableMapEventData = (TableMapEventData) data;
            String database = tableMapEventData.getDatabase();
            String table = tableMapEventData.getTable();
            WebsocketService websocketService = new WebsocketService();
            if ("你的数据库表".equalsIgnoreCase(table)) {
                websocketService.groupSending("你的数据库表字段");
            }
            if ("你的数据库表".equalsIgnoreCase(table)) {
                websocketService.groupSending("你的数据库表字段");
            }
        } else if (data instanceof UpdateRowsEventData) {
            System.out.println("更新:");
            System.out.println(data.toString());
        } else if (data instanceof WriteRowsEventData) {
            System.out.println("添加:");
            System.out.println(data.toString());
        } else if (data instanceof DeleteRowsEventData) {
            System.out.println("删除:");
            System.out.println(data.toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
});

성공적인 연결, 통신 예외, 이벤트 데이터 구문 분석 예외 및 연결 끊김을 처리하기 위해 라이프사이클 리스너를 등록합니다.

client.registerLifecycleListener(new BinaryLogClient.LifecycleListener() {
    @Override
    public void onConnect(BinaryLogClient client) {
        System.out.println("MySQL数据库已连接!");
    }

    @Override
    public void onCommunicationFailure(BinaryLogClient client, Exception ex) {
        System.out.println("已执行通信故障方法!");
        ex.printStackTrace();
    }

    @Override
    public void onEventDeserializationFailure(BinaryLogClient client, Exception ex) {
        System.out.println("已执行反质化方法!");
        ex.printStackTrace();
    }

    @Override
    public void onDisconnect(BinaryLogClient client) {
        System.out.println("MySQL数据库已断开!");
        startReconnectTimer();
    }
});

3. 비공개 방법, 재연결 타이머 시작

기능은 다음과 같습니다:

private static void startReconnectTimer() {

재연결 타이머가 이미 존재하는 경우 이전에 예약된 작업을 먼저 취소하세요.

if (reconnectTimer != null) {
    reconnectTimer.cancel();
}

새로운 재연결 타이머를 생성하고 예약된 작업을 실행하세요. 예약된 작업은 MySQL 서버에 다시 연결을 시도합니다.

reconnectTimer = new Timer();
reconnectTimer.schedule(new TimerTask() {
    @Override
    public void run() {
        boolean isConnected = client != null && client.isConnected();
        try {
            if (isConnected) {
                System.out.println("和数据库断开连接。重连。。。。。。");
                client.disconnect();
            }
            client.connect();
        } catch (IOException e) {
            e.printStackTrace();
            startReconnectTimer();
        }
    }
}, RECONNECT_INTERVAL);
}

전체 코드에 대한 설명이며, MySQL 데이터베이스의 변경 이벤트를 모니터링하고 이에 따라 처리할 수 있는 MySQL Binlog 리스너를 구현합니다.

4. 완전한 코드

비공개 채팅이 필요합니다. . . . . .

Supongo que te gusta

Origin blog.csdn.net/Lushengshi/article/details/130829848
Recomendado
Clasificación