mysql+mycat高可用集群搭建

需要的安装包

mysql安装包

mysql-community-client-5.7.29-1.el7.x86_64.rpm
mysql-community-common-5.7.29-1.el7.x86_64.rpm
mysql-community-libs-5.7.29-1.el7.x86_64.rpm
mysql-community-server-5.7.29-1.el7.x86_64.rpm

mysql安装

一、先删除以前安装过的mysql或者maribad

rpm -qa maribad* | xargs rpm -e --nodeps

二、再按顺序安装mysql包

rpm -ivh [1.common 2.libs 3.client 4.server]

三、修改mysql的密码
方式一:
  1.找到初始化的密码(centos7和cento6.5不一样,6.5在命令行使用mysql就可以进入数据库命令行,而centos7需要输入密码)
   在 vim /var/log/mysqld.log
  2.登录mysql,然后修改密码
   set global validate_password_policy=0;
   set global validate_password_length=1;
   alter user ‘root’@‘localhost’ identified by ‘123456’;

方式二:修改mysql7的密码
  1.修改文件:vim /etc/my.cnf 增加:
  scrpt   skip-grant-tables
  2.重启mysql服务
  script   systemctl restart mysqld.service
  3.使用mysql -u root -p
  4.use mysql;
  5.修改密码:
  script   update mysql.user set authentication_string=password('Tyhy_123456') where user='root' and Host = 'localhost';
  6.刷新权限: flush privileges;

四、修改root访问权限

  1.GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'Tyhy_123456' WITH GRANT OPTION;
  2.flush privileges;

五、删除其他权限并重新登录:

  delete from user where host='localhost';

mysql集群配置

192.168.0.233和192.168.0.232互为主主

192.168.0.233:
grant replication slave on *.* to 'repl_user'@'192.168.0.232' identified by 'Tyhy_123456';
 show master status;
192.168.0.232:
change master to master_host='192.168.0.233', master_user='repl_user',master_password='Tyhy_123456',master_log_file='mysql-bin.000001',master_log_pos=454;
start slave;
show slave status\G;

192.168.0.232:
grant replication slave on *.* to 'repl_user1'@'192.168.0.233' identified by 'Tyhy_123456';
 show master status;
192.168.0.233:
change master to master_host='192.168.0.232', master_user='repl_user1',master_password='Tyhy_123456',master_log_file='mysql-bin.000001',master_log_pos=739418;
start slave;
show slave status\G;

192.168.0.233的/etc/my.cnf配置

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
character_set_server = utf8

back_log=1024
max_connections = 10000
max_connect_errors = 1000
read_buffer_size = 4M
query_cache_size = 64M
key_buffer_size=400M
max_allowed_packet=128M
innodb_flush_log_at_trx_commit=0
innodb_log_file_size = 200M
innodb_log_files_in_group = 3
innodb_buffer_pool_size = 2048M
innodb_log_buffer_size = 16M
query_cache_size = 0
#init_connect='SET autocommit=0'
innodb_lock_wait_timeout = 50
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Recommended in standard MySQL setup
# sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
#sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
sql_mode ='STRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
#replication setting
server-id=1
log-bin=mysql-bin
relay-log=mysql-relay-bin
binlog-do-db=order-center
binlog-do-db=order-center-01
binlog-do-db=order-center-02
binlog-ignore-db=mysql
binlog-ignore-db=performance_schema
binlog-ignore-db=information_schema
binlog-ignore-db=wechat-activity
binlog-ignore-db=sys
log_slave_updates=1
master-info-repository=table
relay-log-info-repository=table
relay-log-recovery=1
##for mmm setting
##read_only=1
##general log
general_log=1
general_log_file=/var/log/mysql/mysql-row.log
##no lower_case
lower_case_table_names = 1
##slow log
slow_query_log=1
slow_query_log_file=/var/log/mysql/mysql-slow.log
long_query_time=2
log-queries-not-using-indexes
#default timestamp
explicit_defaults_for_timestamp=true


[mysqld_sale]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
#skip-grant-tables

192.168.0.232的/etc/my.cnf配置

# For advice on how to change settings please see
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
character_set_server = utf8

back_log=1024
max_connections = 10000
max_connect_errors = 1000
read_buffer_size = 4M
query_cache_size = 64M
key_buffer_size=400M
max_allowed_packet=128M
innodb_flush_log_at_trx_commit=0
innodb_log_file_size = 200M
innodb_log_files_in_group = 3
innodb_buffer_pool_size = 2048M
innodb_log_buffer_size = 16M
query_cache_size = 0
#init_connect='SET autocommit=0'
innodb_lock_wait_timeout = 50
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Recommended in standard MySQL setup
# sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
#replication setting
server-id=2
log-bin=mysql-bin
relay-log=mysql-relay-bin
binlog-do-db=order-center
binlog-do-db=order-center-01
binlog-do-db=order-center-02
binlog-ignore-db=mysql
binlog-ignore-db=performance_schema
binlog-ignore-db=information_schema
binlog-ignore-db=wechat-activity
binlog-ignore-db=sys
log_slave_updates=1
master-info-repository=table
relay-log-info-repository=table
relay-log-recovery=1
##for mmm setting
##read_only=1
##general log
general_log=1
general_log_file=/var/log/mysql/mysql-row.log
##no lower_case
lower_case_table_names = 1
##slow log
slow_query_log=1
slow_query_log_file=/var/log/mysql/mysql-slow.log
long_query_time=2
log-queries-not-using-indexes
#default timestamp
explicit_defaults_for_timestamp=true


[mysqld_sale]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
#skip-grant-tables

192.168.0.232和192.168.0.231互为主备

192.168.0.232:
grant replication slave on *.* to 'repl_user2'@'192.168.0.231' identified by 'Tyhy_123456';
 show master status;
192.168.0.231
##重新修改 需要停止 slave: stop slave;
change master to master_host='192.168.0.232', master_user='repl_user2',master_password='Tyhy_123456',master_log_file='mysql-bin.000001',master_log_pos=739711;
start slave;
show slave status\G;

192.168.0.231的/etc/my.cnf配置

#For advice on how to change settings please see
#http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html

[mysqld]
#
# Remove leading # and set to the amount of RAM for the most important data
# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.
# innodb_buffer_pool_size = 128M
#
# Remove leading # to turn on a very important data integrity option: logging
# changes to the binary log between backups.
# log_bin
#
# Remove leading # to set options mainly useful for reporting servers.
# The server defaults are faster for transactions and fast SELECTs.
# Adjust sizes as needed, experiment to find the optimal values.
# join_buffer_size = 128M
# sort_buffer_size = 2M
# read_rnd_buffer_size = 2M
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
character_set_server = utf8

back_log=1024
max_connections = 10000
max_connect_errors = 1000
read_buffer_size = 4M
query_cache_size = 64M
key_buffer_size=400M
max_allowed_packet=128M
innodb_flush_log_at_trx_commit=0
innodb_log_file_size = 200M
innodb_log_files_in_group = 3
innodb_buffer_pool_size = 2048M
innodb_log_buffer_size = 16M
query_cache_size = 0
#init_connect='SET autocommit=0'
innodb_lock_wait_timeout = 50
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Recommended in standard MySQL setup
# sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES
sql_mode ='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'
#replication setting
server-id=3
#log-bin=mysql-bin
relay-log=mysql-relay-bin
binlog-do-db=order-center
binlog-do-db=order-center-01
binlog-do-db=order-center-02
binlog-ignore-db=mysql
binlog-ignore-db=performance_schema
binlog-ignore-db=information_schema
binlog-ignore-db=wechat-activity
binlog-ignore-db=sys
#log_slave_updates=1
master-info-repository=table
relay-log-info-repository=table
relay-log-recovery=1
##for mmm setting
read_only=1
##general log
general_log=1
general_log_file=/var/log/mysql/mysql-row.log
##no lower_case
lower_case_table_names = 1
##slow log
slow_query_log=1
slow_query_log_file=/var/log/mysql/mysql-slow.log
long_query_time=2
log-queries-not-using-indexes
#default timestamp
explicit_defaults_for_timestamp=true


[mysqld_sale]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid
#skip-grant-tables

mycat安装包

Mycat-server-1.6-RELEASE-20161028204710-linux.tar.gz

mycat的安装

schema配置
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://io.mycat/">

	<!--
		schema :声明mycat的虚拟数据库
	-->
	<schema name="orderCenter" checkSQLschema="true" >
	        <!-- auto sharding by id (long) -->
                <!--订单表和订单明细表-->
                <table name="car_order" dataNode="dn1,dn2,dn3" rule="mod-long"/>
                <!-- 订单支付表 -->
                <table name="pay_order" dataNode="dn1,dn2,dn3" rule="mod-long" />
		<!-- 商品明细表 -->
                <table name="car_order_item" dataNode="dn1,dn2,dn3" rule="mod-long" />
		<!-- 卡券明细表-->
                <table name="car_order_item_coupon" dataNode="dn1,dn2,dn3" rule="mod-long" />
                <!-- 卡券订单明细 -->
                <table name="car_order_item_coupon_many" dataNode="dn1,dn2,dn3" rule="mod-long" />

                <!-- 其他全局表 -->
                <table name="pay_refund" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="base_org" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="merchant" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="pay_channel" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="pay_type" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="merchant_org" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="bill_job" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="bill_trans" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
                <table name="order_reconciliation" dataNode="dn1,dn2,dn3" type="global" primaryKey="id" />
		<!-- 测试:这里如果有外键关联的话 使用java调用写语句 如果子表没有order_id没有关联父表id会报错,但是在mycat客户端执行不关联 不会报错 -->
		<table name="test_order" dataNode="dn1,dn2,dn3" rule="mod-long" >
	
			<childTable name="test_item" primaryKey="id" joinKey="order_id"
						parentKey="id">
			</childTable>
			<childTable name="test_item_coupon" primaryKey="id" joinKey="order_id"
						parentKey="id">
			</childTable>
			
		</table>

	</schema>
	<!--
		dataNode : 声明数据分片
		   name : 分片名称
		   dataHost : 声明分片主机
		   database : 分片对应的后台物理表
	-->
	<dataNode name="dn1" dataHost="orderHost" database="order-center" />
	<dataNode name="dn2" dataHost="orderHost" database="order-center-01" />
	<dataNode name="dn3" dataHost="orderHost" database="order-center-02" />
	
	<!-- dataHost:声明分片主机
	        name:主机名字

	-->
	<dataHost name="orderHost" maxCon="1000" minCon="10" balance="1"
			  writeType="0" dbType="mysql" dbDriver="native" switchType="1"  slaveThreshold="100">
		<!-- 实现mycat和后台主机之间的心跳检测 -->
		<heartbeat>select user()</heartbeat>
		<writeHost host="hostM2" url="192.168.0.233:3306" user="root" password="Tyhy_123456"/> 
			<!-- 声明写的主机 -->
		<writeHost host="hostM1" url="192.168.0.232:3306" user="root"   password="Tyhy_123456">
			<!-- 声明读的主机 -->
			 <readHost host="hostS1" url="192.168.0.231:3306" user="root" password="Tyhy_123456" />
		</writeHost>
	</dataHost>
	<!--
		<dataHost name="sequoiadb1" maxCon="1000" minCon="1" balance="0" dbType="sequoiadb" dbDriver="jdbc">
		<heartbeat> 		</heartbeat>
		 <writeHost host="hostM1" url="sequoiadb://1426587161.dbaas.sequoialab.net:11920/SAMPLE" user="jifeng" 	password="jifeng"></writeHost>
		 </dataHost>

	  <dataHost name="oracle1" maxCon="1000" minCon="1" balance="0" writeType="0" 	dbType="oracle" dbDriver="jdbc"> <heartbeat>select 1 from dual</heartbeat>
		<connectionInitSql>alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss'</connectionInitSql>
		<writeHost host="hostM1" url="jdbc:oracle:thin:@127.0.0.1:1521:nange" user="base" 	password="123456" > </writeHost> </dataHost>

		<dataHost name="jdbchost" maxCon="1000" 	minCon="1" balance="0" writeType="0" dbType="mongodb" dbDriver="jdbc">
		<heartbeat>select 	user()</heartbeat>
		<writeHost host="hostM" url="mongodb://192.168.0.99/test" user="admin" password="123456" ></writeHost> </dataHost>

		<dataHost name="sparksql" maxCon="1000" minCon="1" balance="0" dbType="spark" dbDriver="jdbc">
		<heartbeat> </heartbeat>
		 <writeHost host="hostM1" url="jdbc:hive2://feng01:10000" user="jifeng" 	password="jifeng"></writeHost> </dataHost> -->

	<!-- <dataHost name="jdbchost" maxCon="1000" minCon="10" balance="0" dbType="mysql"
		dbDriver="jdbc"> <heartbeat>select user()</heartbeat> <writeHost host="hostM1"
		url="jdbc:mysql://localhost:3306" user="root" password="123456"> </writeHost>
		</dataHost> -->
</mycat:schema>

server.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
	- you may not use this file except in compliance with the License. - You 
	may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 
	- - Unless required by applicable law or agreed to in writing, software - 
	distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
	License for the specific language governing permissions and - limitations 
	under the License. -->
<!DOCTYPE mycat:server SYSTEM "server.dtd">
<mycat:server xmlns:mycat="http://io.mycat/">
	<system>
	<property name="useSqlStat">0</property>  <!-- 1为开启实时统计、0为关闭 -->
	<property name="useGlobleTableCheck">0</property>  <!-- 1为开启全加班一致性检测、0为关闭 -->

		<property name="sequnceHandlerType">2</property>
      <!--  <property name="useCompression">1</property>--> <!--1为开启mysql压缩协议-->
        <!--  <property name="fakeMySQLVersion">5.6.20</property>--> <!--设置模拟的MySQL版本号-->
	<!-- <property name="processorBufferChunk">40960</property> -->
	<!-- 
	<property name="processors">1</property> 
	<property name="processorExecutor">32</property> 
	 -->
		<!--默认为type 0: DirectByteBufferPool | type 1 ByteBufferArena-->
		<property name="processorBufferPoolType">0</property>
		<!--默认是65535 64K 用于sql解析时最大文本长度 -->
		<!--<property name="maxStringLiteralLength">65535</property>-->
		<!--<property name="sequnceHandlerType">0</property>-->
		<!--<property name="backSocketNoDelay">1</property>-->
		<!--<property name="frontSocketNoDelay">1</property>-->
		<!--<property name="processorExecutor">16</property>-->
		<!--
			<property name="serverPort">8066</property> <property name="managerPort">9066</property> 
			<property name="idleTimeout">300000</property> <property name="bindIp">0.0.0.0</property> 
			<property name="frontWriteQueueSize">4096</property> <property name="processors">32</property> -->
		<!--分布式事务开关,0为不过滤分布式事务,1为过滤分布式事务(如果分布式事务内只涉及全局表,则不过滤),2为不过滤分布式事务,但是记录分布式事务日志-->
		<property name="handleDistributedTransactions">0</property>
		
			<!--
			off heap for merge/order/group/limit      1开启   0关闭
		-->
		<property name="useOffHeapForMerge">1</property>

		<!--
			单位为m
		-->
		<property name="memoryPageSize">1m</property>

		<!--
			单位为k
		-->
		<property name="spillsFileBufferSize">1k</property>

		<property name="useStreamOutput">0</property>

		<!--
			单位为m
		-->
		<property name="systemReserveMemorySize">384m</property>


		<!--是否采用zookeeper协调切换  -->
		<property name="useZKSwitch">true</property>


	</system>
	
	<!-- 全局SQL防火墙设置 -->
	<!-- 
	<firewall> 
	   <whitehost>
	      <host host="127.0.0.1" user="mycat"/>
	      <host host="127.0.0.2" user="mycat"/>
	   </whitehost>
       <blacklist check="false">
       </blacklist>
	</firewall>
	-->
	
	<user name="root">
		<property name="password">root</property>
		<property name="schemas">orderCenter</property>
		
		<!-- 表级 DML 权限设置 -->
		<!-- 		
		<privileges check="false">
			<schema name="TESTDB" dml="0110" >
				<table name="tb01" dml="0000"></table>
				<table name="tb02" dml="1111"></table>
			</schema>
		</privileges>		
		 -->
	</user>

	<user name="tyhy">
		<property name="password">tyhy</property>
		<property name="schemas">orderCenter</property>
		<property name="readOnly">true</property>
	</user>

</mycat:server>

rule.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<!-- - - Licensed under the Apache License, Version 2.0 (the "License"); 
	- you may not use this file except in compliance with the License. - You 
	may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 
	- - Unless required by applicable law or agreed to in writing, software - 
	distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 
	WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the 
	License for the specific language governing permissions and - limitations 
	under the License. -->
<!DOCTYPE mycat:rule SYSTEM "rule.dtd">
<mycat:rule xmlns:mycat="http://io.mycat/">
	<tableRule name="rule1">
		<rule>
			<columns>id</columns>
			<algorithm>func1</algorithm>
		</rule>
	</tableRule>

	<tableRule name="rule2">
		<rule>
			<columns>user_id</columns>
			<algorithm>func1</algorithm>
		</rule>
	</tableRule>

	<tableRule name="sharding-by-intfile">
		<rule>
			<columns>sharding_id</columns>
			<algorithm>hash-int</algorithm>
		</rule>
	</tableRule>
	<tableRule name="auto-sharding-long">
		<rule>
			<columns>id</columns>
			<algorithm>rang-long</algorithm>
		</rule>
	</tableRule>
	<tableRule name="mod-long">
		<rule>
			<columns>id</columns>
			<algorithm>mod-long</algorithm>
		</rule>
	</tableRule>
	<tableRule name="sharding-by-murmur">
		<rule>
			<columns>id</columns>
			<algorithm>murmur</algorithm>
		</rule>
	</tableRule>
	<tableRule name="crc32slot">
		<rule>
			<columns>id</columns>
			<algorithm>crc32slot</algorithm>
		</rule>
	</tableRule>
	<tableRule name="sharding-by-month">
		<rule>
			<columns>create_time</columns>
			<algorithm>partbymonth</algorithm>
		</rule>
	</tableRule>
	<tableRule name="latest-month-calldate">
		<rule>
			<columns>calldate</columns>
			<algorithm>latestMonth</algorithm>
		</rule>
	</tableRule>
	
	<tableRule name="auto-sharding-rang-mod">
		<rule>
			<columns>id</columns>
			<algorithm>rang-mod</algorithm>
		</rule>
	</tableRule>
	
	<tableRule name="jch">
		<rule>
			<columns>id</columns>
			<algorithm>jump-consistent-hash</algorithm>
		</rule>
	</tableRule>

	<function name="murmur"
		class="io.mycat.route.function.PartitionByMurmurHash">
		<property name="seed">0</property><!-- 默认是0 -->
		<property name="count">2</property><!-- 要分片的数据库节点数量,必须指定,否则没法分片 -->
		<property name="virtualBucketTimes">160</property><!-- 一个实际的数据库节点被映射为这么多虚拟节点,默认是160倍,也就是虚拟节点数是物理节点数的160倍 -->
		<!-- <property name="weightMapFile">weightMapFile</property> 节点的权重,没有指定权重的节点默认是1。以properties文件的格式填写,以从0开始到count-1的整数值也就是节点索引为key,以节点权重值为值。所有权重值必须是正整数,否则以1代替 -->
		<!-- <property name="bucketMapPath">/etc/mycat/bucketMapPath</property> 
			用于测试时观察各物理节点与虚拟节点的分布情况,如果指定了这个属性,会把虚拟节点的murmur hash值与物理节点的映射按行输出到这个文件,没有默认值,如果不指定,就不会输出任何东西 -->
	</function>

	<function name="crc32slot"
			  class="io.mycat.route.function.PartitionByCRC32PreSlot">
		<property name="count">2</property><!-- 要分片的数据库节点数量,必须指定,否则没法分片 -->
	</function>
	<function name="hash-int"
		class="io.mycat.route.function.PartitionByFileMap">
		<property name="mapFile">partition-hash-int.txt</property>
	</function>
	<function name="rang-long"
		class="io.mycat.route.function.AutoPartitionByLong">
		<property name="mapFile">autopartition-long.txt</property>
	</function>
	<function name="mod-long" class="io.mycat.route.function.PartitionByMod">
		<!-- how many data nodes -->
		<property name="count">3</property>
	</function>

	<function name="func1" class="io.mycat.route.function.PartitionByLong">
		<property name="partitionCount">8</property>
		<property name="partitionLength">128</property>
	</function>
	<function name="latestMonth"
		class="io.mycat.route.function.LatestMonthPartion">
		<property name="splitOneDay">24</property>
	</function>
	<function name="partbymonth"
		class="io.mycat.route.function.PartitionByMonth">
		<property name="dateFormat">yyyy-MM-dd</property>
		<property name="sBeginDate">2015-01-01</property>
	</function>
	
	<function name="rang-mod" class="io.mycat.route.function.PartitionByRangeMod">
        	<property name="mapFile">partition-range-mod.txt</property>
	</function>
	
	<function name="jump-consistent-hash" class="io.mycat.route.function.PartitionByJumpConsistentHash">
		<property name="totalBuckets">3</property>
	</function>
</mycat:rule>

mycat 启动

/bin/mycat start

xinetd安装

1.安装xinetd
yum install xinetd
2.在xinetd中添加 includedir /etc/xinetd.d 不存在就加
vi /etc/xinetd.conf
3.创建/etc/xinetd.d 目录 不存在就新建
mkdir -p /etc/xinetd.d/
4、增加Mycat存活状态检测服务配置
touch /etc/xinetd.d/mycat_status
vi /etc/xinetd.d/mycat_status
增加内容:
	service mycat_status
	{
	flags = REUSE
	## 使用该标记的socket_type为stream,需要设置wait为no
	socket_type = stream ## 封包处理方式,Stream为TCP数据包
	port = 48700 ## 服务监听端口
	wait = no ## 表示不需等待,即服务将以多线程的方式运行
	user = root ## 执行此服务进程的用户
	server =/usr/local/bin/mycat_status ## 需要启动的服务脚本
	log_on_failure += USERID ## 登录失败记录的内容
	disable = no ## 要启动服务,将此参数设置为no
	}
5、添加 /usr/local/bin/mycat_status 服务脚本
touch /usr/local/bin/mycat_status
vi /usr/local/bin/mycat_status
增加内容:
	#!/bin/bash
	#/usr/local/bin/mycat_status.sh
	# This script checks if a Mycat server is healthy running on localhost.
	# It will return:
	# "HTTP/1.x 200 OK\r" (if Mycat is running smoothly)
	# "HTTP/1.x 503 Internal Server Error\r" (else)
	Mycat=`/usr/local/Mycat/bin/mycat status | grep 'not running' | wc -l`
	if [ "$Mycat" = "0" ]; then
	/bin/echo -e "HTTP/1.1 200 OK\r\n"
	else
	/bin/echo -e "HTTP/1.1 503 Service Unavailable\r\n"
	fi
6、给新增脚本赋予可执行权限
chmod a+x /usr/local/bin/mycat_status
7、在 /etc/services 中加入 mycat_status 服务
vi /etc/services
在末尾加入:
	mycat_status 48700/tcp # mycat_status
8.保存后,重启xinetd服务
service xinetd restart
9.验证mycat_status服务是否成功启动
netstat -antup|grep 48700

haproxy安装包

haproxy-1.8.1.tar.gz

安装haproxy

1、下载(或上传) haproxy-1.5.19.tar.gz 到 /usr/local/src,解压安装
[root@liuyazhuang135 src]# cd /usr/local/src/
下载地址:https://src.fedoraproject.org/repo/pkgs/haproxy/
[root@liuyazhuang135 src]# tar -zxvf haproxy-1.5.19.tar.gz
[root@liuyazhuang135 src]# cd haproxy-1.5.19

2.安装依赖包
yum install gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel

3.编译
make TARGET=linux2628 ARCH=x86_64 USE_PCRE=1 USE_OPENSSL=1 USE_ZLIB=1 PREFIX=/opt/app/haproxy

mkdir /opt/app/haproxy

make install PREFIX=/opt/app/haproxy
4. 拷贝配置文件。错误页面文件夹。启动项到对应目录 ,并创建软连接
mkdir -p  /opt/app/haproxy/conf
mkdir -p /etc/haproxy/

cp /opt/app/haproxy-1.8.1/examples/haproxy.cfg /opt/app/haproxy/conf/
ln -s /opt/app/haproxy/conf/haproxy.cfg  /etc/haproxy/haproxy.cfg

cp -r /opt/app/haproxy-1.8.1/examples/errorfiles /opt/app/haproxy/
ln -s /opt/app/haproxy/errorfiles/ /etc/haproxy/errorfiles

cp /opt/app/haproxy-1.8.1/examples/haproxy.init /etc/rc.d/init.d/haproxy
chmod +x /etc/rc.d/init.d/haproxy

5.开机自启动
ln -s /opt/app/haproxy/sbin/haproxy /usr/sbin/haproxy
chkconfig --add haproxy
chkconfig haproxy on

5.配置haproxy
#---------------------------------------------------------------------
# Example configuration for a possible web application.  See the
# full configuration options online.
#
#   http://haproxy.1wt.eu/download/1.4/doc/configuration.txt
#
#---------------------------------------------------------------------

#---------------------------------------------------------------------
# Global settings
#---------------------------------------------------------------------
global
    # to have these messages end up in /var/log/haproxy.log you will
    # need to:
    #
    # 1) configure syslog to accept network log events.  This is done
    #    by adding the '-r' option to the SYSLOGD_OPTIONS in
    #    /etc/sysconfig/syslog
    #
    # 2) configure local2 events to go to the /var/log/haproxy.log
    #   file. A line like the following can be added to
    #   /etc/sysconfig/syslog
    #
    #    local2.*                       /var/log/haproxy.log
    #
    log         127.0.0.1 local2 info

    chroot      /usr/share/haproxy
    group       haproxy
    user        haproxy
    daemon
    nbproc       1
   # pidfile     /var/run/haproxy.pid
    maxconn     4000
    node        node03
    description node03
    # turn on stats unix socket
    #stats socket /var/lib/haproxy/stats

#---------------------------------------------------------------------
# common defaults that all the 'listen' and 'backend' sections will
# use if not designated in their block
#---------------------------------------------------------------------
defaults
    mode                    http
    log                     global
    option                  httplog
    option                  dontlognull
    option http-server-close
    option forwardfor       except 127.0.0.0/8
    option                  redispatch
    retries                 3
    timeout http-request    10s
    timeout queue           1m
    timeout connect         10s
    timeout client          1m
    timeout server          1m
    timeout http-keep-alive 10s
    timeout check           10s
    maxconn                 3000

#haproxy的状态信息统计页面
listen admin_stats
   bind  :48800
   stats  uri     /admin-status 
   stats  auth    admin:admin
   mode   http
   option httplog
#mycat配置
listen mycat_services
   bind  :3307
   mode  tcp
   option tcplog
   option tcpka
   option httpchk OPTIONS * HTTP/1.1\r\nHost:\ www
   balance roundrobin
   server mycat_01 192.168.0.231:8066 check port 48700 inter 2000ms rise 2 fall 3 weight 10
   server mycat_02 192.168.0.232:8066 check port 48700 inter 2000ms rise 2 fall 3 weight 10
   server mycat_03 192.168.0.233:8066 check port 48700 inter 2000ms rise 2 fall 3 weight 10

   
(1)添加haproxy用户组和用户
 groupadd haproxy
 useradd -g haproxy haproxy
 
(2)创建chroot运行的路径
mkdir /usr/share/haproxy

(3) 启动haproxy
service haproxy start
ps -ef | grep haproxy

(4) 验证连接mycat
haproxy端口是3307

管理页面:http://192.168.0.233:48800/admin-status admin:admin

安装rsyslog

1.安装rsyslog
yum install rsyslog ## 没安装的情况下执行安装
2.修改rsyslog.conf
# vi /etc/rsyslog.conf
一。把 $ModLoad imudp 和 $UDPServerRun 514前面的 # 去掉
$ModLoad imudp ## 是模块名,支持UDP协议
$UDPServerRun 514
##允许514端口接收使用UDP和TCP协议转发过来的日志,
##而rsyslog在默认情况下,正是在514端口监听UDP
确认 #### GLOBAL DIRECTIVES #### 段中是否有: $IncludeConfig /etc/rsyslog.d/*.conf 没有则增加上此配置。
3.新建文件并增加配置
  cd /etc/rsyslog.d/ ## rsyslog服务会来此目录加载配置
touch haproxy.conf ## 创建haproxy的日志配置文件
vi /etc/rsyslog.d/haproxy.conf
  增加以下内容:
		local0.* /var/log/haproxy.log

		&~
  注意:如果不加上面的的"&~"配置则除了在/var/log/haproxy.log中写入日志外,也会写入/var/log/message文件中
 4.保存重启
 service rsyslog restart
 5.配置系统内核的IP包转发功能
 # vi /etc/sysctl.conf
	net.ipv4.ip_forward = 1
  生效命令:# sysctl -p

keepalived安装包

keepalived-1.3.4.tar.gz

keepalived安装

下载地址:https://www.keepalived.org/download.html
 1.安装keepalived
  yum install gcc gcc-c++ openssl openssl-devel
 mkdir -p /opt/app/keepalived
 cd /opt/app/
 tar -zxvf keepalived-1.2.18.tar.gz
 cd keepalived-1.2.18
 ./configure --prefix=/opt/app/keepalived
 make && make install
 2.设置成系统服务
 mkdir -p /etc/keepalived
cp /opt/app/keepalived-1.3.4/keepalived/etc/keepalived/keepalived.conf /etc/keepalived/

cp /opt/app/keepalived-1.3.4/keepalived/etc/init.d/keepalived /etc/init.d/
cp /opt/app/keepalived-1.3.4/keepalived/etc/sysconfig/keepalived /etc/sysconfig/
ln -s /opt/app/keepalived/sbin/keepalived /usr/sbin/
#ln -s /opt/app/keepalived/sbin/keepalived /sbin/keepalived

chkconfig keepalived on

service keepalived start/status/stop/restart

3.主配置
! Configuration File for keepalived
global_defs {
## keepalived 自带的邮件提醒需要开启 sendmail 服务。建议用独立的监控或第三方 SMTP
	router_id node01 ## 标识本节点的字条串,通常为 hostname
}
## keepalived 会定时执行脚本并对脚本执行的结果进行分析,动态调整 vrrp_instance 的优先级。
## 如果脚本执行结果为 0,并且 weight 配置的值大于 0,则优先级相应的增加。
## 如果脚本执行结果非 0,并且 weight 配置的值小于 0,则优先级相应的减少。
## 其他情况,维持原本配置的优先级,即配置文件中 priority 对应的值。
vrrp_script chk_haproxy {
	script "/etc/keepalived/haproxy_check.sh" ## 检测 haproxy 状态的脚本路径
	interval 2 ## 检测时间间隔
	weight 2 ## 如果条件成立,权重+2
}
## 定义虚拟路由, VI_1 为虚拟路由的标示符,自己定义名称
vrrp_instance VI_1 {
	state BACKUP ## 默认主设备(priority 值大的)和备用设备(priority 值小的)都设置为 BACKUP,
	## 由 priority 来控制同时启动情况下的默认主备,否则先启动的为主设备
	interface ens192 ## 绑定虚拟 IP 的网络接口,与本机 IP 地址所在的网络接口相同,我的是 eth3
	virtual_router_id 35 ## 虚拟路由的 ID 号,两个节点设置必须一样,可选 IP 最后一段使用,
	## 相同的 VRID 为一个组,他将决定多播的 MAC 地址
	priority 120 ## 节点优先级,值范围 0-254, MASTER 要比 BACKUP 高
	nopreempt ## 主设备(priority 值大的)配置一定要加上 nopreempt,否则非抢占也不起作用
	advert_int 1 ## 组播信息发送间隔,两个节点设置必须一样,默认 1s
	## 设置验证信息,两个节点必须一致
	authentication {
		auth_type PASS
		auth_pass 1111 ## 真实生产,按需求对应该过来
	}
	## 将 track_script 块加入 instance 配置块
	track_script {
		chk_haproxy ## 检查 HAProxy 服务是否存活
	}
	## 虚拟 IP 池, 两个节点设置必须一样
	virtual_ipaddress {
		192.168.0.110 ## 虚拟 ip,可以定义多个,每行一个
	}
}

#备配置
! Configuration File for keepalived
global_defs {
	router_id node02
}
vrrp_script chk_haproxy {
	script "/etc/keepalived/haproxy_check.sh"
	interval 2
	weight 2
}
vrrp_instance VI_1 {
	state BACKUP
	interface ens192
	virtual_router_id 35
	priority 110
	advert_int 1
	authentication {
		auth_type PASS
		auth_pass 1111
	}
	track_script {
		chk_haproxy
	}
	virtual_ipaddress {
		192.168.0.110 ## 虚拟 ip,可以定义多个,每行一个
	}
}
4.##配置监听haproxy的脚本
#!/bin/bash
START_HAPROXY="/etc/rc.d/init.d/haproxy start"
STOP_HAPROXY="/etc/rc.d/init.d/haproxy stop"
LOG_FILE="/opt/app/keepalived/logs/log/haproxy-check.log"
HAPS=`ps -C haproxy --no-header |wc -l`
date "+%Y-%m-%d %H:%M:%S" >> $LOG_FILE
echo "check haproxy status" >> $LOG_FILE
if [ $HAPS -eq 0 ];then
echo $START_HAPROXY >> $LOG_FILE
$START_HAPROXY >> $LOG_FILE 2>&1
sleep 3
if [ `ps -C haproxy --no-header |wc -l` -eq 0 ];then
echo "start haproxy failed, killall keepalived" >> $LOG_FILE
killall keepalived
fi
fi

5.测试haproxy+keepalived
 a. 关闭 keepalived所在机器的haproxy,keepalived会自动启动haproxy
 b. 关闭 keepalive服务 另外一台keepalived会抢占vip 
 使用ip addr 查看虚拟ip在哪台机器上
 在windows上查看 keepalived的服务ip 查看mac地址
 然后查看 vip虚拟ip在哪台机器上 arp -a  ip地址
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值