PHP与canal使用canal-php记录

@高效码农  April 1, 2022

安装Canal

Canal 的安装以及配置使用请查看 https://github.com/alibaba/canal/wiki/QuickStart

安装canal-php canal php客户端

$ composer require xingwenge/canal_php

or

$ git clone https://github.com/xingwenge/canal-php.git
$ cd canal-php
$ composer update

测试链接

第一种方式PHP CLI(命令行)
代码如下
<?php
namespace xingwenge\canal_php\sample;

use xingwenge\canal_php\CanalClient;
use xingwenge\canal_php\CanalConnectorFactory;
use xingwenge\canal_php\Fmt;

require_once __DIR__. '/../../vendor/autoload.php';

ini_set('display_errors', 'On');
error_reporting(E_ALL);

try {
    $client = CanalConnectorFactory::createClient(CanalClient::TYPE_SOCKET_CLUE);
    # $client = CanalConnectorFactory::createClient(CanalClient::TYPE_SWOOLE);

    $client->connect("192.168.1.210", 36525);
//    $client->checkValid();
    $client->subscribe("1001", "blogs_ins", ".*\\..*");
    # $client->subscribe("1001", "example", "db_name.tb_name"); # 设置过滤

    while (true) {
        $message = $client->get(100);
        if ($entries = $message->getEntries()) {
            foreach ($entries as $entry) {
                Fmt::println($entry);
            }
        }
        sleep(1);
    }

    $client->disConnect();
} catch (\Exception $e) {
    echo $e->getMessage(), PHP_EOL;
}
命令行运行
php src/sample/client.php   
输出:

2022-04-01T08:44:30.png

第二种方式:nginx web 链接
public function index()
    {
        try {
            $client = CanalConnectorFactory::createClient(CanalClient::TYPE_SOCKET_CLUE);
            # $client = CanalConnectorFactory::createClient(CanalClient::TYPE_SWOOLE);

            $client->connect("192.168.1.210", 36525);
            $client->checkValid();
            $client->subscribe("1001", "reanod", ".*\\..*");
            # $client->subscribe("1001", "example", "db_name.tb_name"); # 设置过滤

//            while (true) {
                $message = $client->get(100);
            dump($message);
                if ($entries = $message->getEntries()) {
                    foreach ($entries as $entry) {
                        Fmt::println($entry);
                    }
                }
                sleep(1);
//            }

            $client->disConnect();
        } catch (\Exception $e) {
            echo $e->getMessage(), PHP_EOL;
        }
    }
使用方式在浏览器访问当前链接即可

出现问题:

一、报错信息

TSocket: Could not read 4 bytes from ip:port

解决:

$client = CanalConnectorFactory::createClient(CanalClient::TYPE_SOCKET);
替换为
$client = CanalConnectorFactory::createClient(CanalClient::TYPE_SOCKET_CLUE);

二、没有报错但是获取不到MySQL的binlog

解决方案:添加 $client->checkValid();,并查看canal默认数据库用户名密码是否为canal



添加新评论