主数据库: 172.16.254.21 端口:5432
从数据库: 172.16.254.22 端口:5432
步骤1:主从均安装slon
apt-get install slon-bin
步骤2:主从数据库配置权限,创建语言。
在主数据库中 vi /etc/postgresql/8.3/node/pg_hba.conf
添加一条记录 host all repl 172.16.254.22/32 md5
在主从数据库均执行以下操作:
shell>psql
node=#create role repl password ‘123456’ login superuser
#创建用户repl,赋予超级用户权限
node=# use node;
node=# create language plpgsql;
#创建语言plpgsql
步骤3:备份主数据库至从数据库并恢复
#在主数据库备份要复制的数据库
pg_dump node > node_20100220.dmp
#在从库恢复数据库node
postgres=#create database node;
postgres=#\q
shell>psql node < node_20100220.dmp ;
步骤4:在从数据库/export/script目录下创建一个脚本replication,内容如下:
#!/bin/sh
SLONIK=/usr/bin/slonik
SLON=/usr/bin/slon
CLUSTER_NAME=mynode
MASTER=”host=172.16.254.21 dbname=node user=repl password=123456″
SLAVE=”host=172.16.254.22 dbname=node user=repl password=123456″
LOG=/root
uninstall()
{
$SLONIK << _EOF_
cluster name = $CLUSTER_NAME;
node 1 admin conninfo = ‘$MASTER';
node 2 admin conninfo = ‘$SLAVE';
# drop node (id = 2);
# drop node (id = 1);
uninstall node (id = 2);
uninstall node (id = 1);
_EOF_
}
install()
{
$SLONIK << _EOF_
# 定义集群名字
cluster name = $CLUSTER_NAME;
# 定义两个节点
node 1 admin conninfo = ‘$MASTER';
node 2 admin conninfo = ‘$SLAVE';
try
{
# 初始化主节点
init cluster (id=1, comment = ‘Master Node’);
# 创建一个复制集合
create set (id=1, origin=1, comment = ‘All tables’);
# 在复制集合中添加一个需要复制的表
set add table ( set id=1, origin=1,id=1, fully qualified name=’public.hxf’,comment=’Table hxf’ );
#set add sequence (set id = 1, origin = 1, id = 3, fully qualified name = ‘public.hxf_seq’);
# 创建从节点
store node (id = 2, comment = ‘Slave node’);
# 定义节点之间的访问路径
store path (server = 1, client = 2, conninfo = ‘$MASTER’);
store path (server = 2, client = 1, conninfo = ‘$SLAVE’);
# 定义事件监听
store listen (origin = 1, provider = 1, receiver = 2);
store listen (origin = 2, provider = 2, receiver = 1);
# 订阅复制集合
subscribe set (id = 1, provider = 1, receiver = 2, forward = no);
}
on success
{
echo ‘Install OK!';
}
on error
{
echo ‘Install FAIL!';
}
_EOF_
}
start()
{
# 启动复制守护进程
$SLON $CLUSTER_NAME “$MASTER” >> /export/scripts/master.log &
$SLON $CLUSTER_NAME “$SLAVE” >> /export/scripts/slave.log &
}
stop()
{
# killall slon
kill -9 `ps axu|grep ‘dbname=node’ |grep -v grep|awk ‘{print $2}’`
}
case $1 in
‘install’)
install
;;
‘uninstall’)
uninstall
;;
‘start’)
start
;;
‘stop’)
stop
;;
*)
echo “usage: $0 {install|uninstall|start|stop} ”
;;
esac
步骤5:启动
./replication start
步骤6:测试
1.在主数据库的空表public.hxf中添加一条记录
insert into hxf(uid,uname) select 1,’huangxifeng';
2.在主数据库中看到有一条记录
node=# select * from hxf;
uid | uname
—–+————-
1 | huangxifeng
(1 row)
3.在从数据库中看到有一条记录
node=# select * from hxf;
uid | uname
—–+————-
1 | huangxifeng
(1 row)