数据库中间件mycat的使用
一、环境 windows server 2008r2(8核 16G内存) 、 sqlserver 、 mysql 、 mycat1.5.2
二、测试前端代码(只提供C#,为了解决公司原有老项目 java的到mycat的github上面自行查找)
数据库操作如下
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class MySQLHelper
{
private static string connectionString = "Server=10.10.3.234;Port=8066;Database=DataCenter_Odds;User=sa;Password=123456;";
private static string SET_ENCODING="utf8";
/// <summary>
/// 执行查询语句,返回DataSet
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
DataSet ds = new DataSet();
try
{
try
{
connection.Open();
}
catch(Exception exp)
{
}
finally
{
MySqlDataAdapter command = new MySqlDataAdapter(SQLString, connection);
command.Fill(ds);
}
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
finally
{
connection.Close();
}
return ds;
}
}
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string SQLString)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, connection))
{
try
{
int rows = 0;
try
{
connection.Open();
}
catch (Exception exp)
{
}
finally
{
rows = cmd.ExecuteNonQuery();
}
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
finally
{
cmd.Dispose();
connection.Close();
}
}
}
}
/// <summary>
/// 执行SQL语句,返回影响的记录数
/// </summary>
/// <param name="SQLString">SQL语句</param>
/// <returns>影响的记录数</returns>
public static int ExecuteSql(string[] arrSql)
{
using (MySqlConnection connection = new MySqlConnection(connectionString))
{
try
{
connection.Open();
MySqlCommand cmdEncoding = new MySqlCommand(SET_ENCODING, connection);
cmdEncoding.ExecuteNonQuery();
int rows = 0;
foreach (string strN in arrSql)
{
using (MySqlCommand cmd = new MySqlCommand(strN, connection))
{
rows += cmd.ExecuteNonQuery();
}
}
return rows;
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw e;
}
finally
{
connection.Close();
}
}
}
}
}
测试代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using System.IO;
using System.Data;
namespace ConsoleApplication1
{
public class Program
{
public static Guid executeFunctionMysql()
{
Guid str = new Guid();
DataSet dataset = MySQLHelper.Query("select * from T_TEST1 where age > 15");
//DataSet dataset = MySQLHelper.Query("select * from actor where first_name = 'PENELOPE' and last_name='GUINESS' limit 1");
DataTable dt = dataset.Tables[0];
//遍历行
foreach (DataRow dr in dt.Rows)
{
//遍历列
for (int i = 0; i < dt.Columns.Count; i++)
{
Console.Write(dr[i].ToString() + " - " );
}
Console.WriteLine();
}
return str;
}
public static int insertData()
{
DateTime start = DateTime.Now;
Console.WriteLine(" 开始时间 " + start.ToString("yyyy-MM-dd HH:mm:ss,sss"));
Random rand = new Random(10000);
for (int i=1; i<10000; i++)
{
MySQLHelper.ExecuteSql("insert into T_TEST1(name,age) values('aaa_"+i+"',"+rand.Next(10000)+")");
}
DateTime end = DateTime.Now;
Console.WriteLine(" 结束时间 " + end.ToString("yyyy-MM-dd HH:mm:ss,sss"));
Console.WriteLine("共花费:" + (end -start).TotalMilliseconds + " 毫秒");
return 0;
}
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(new FileInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log4net.config"));
Console.Write(insertData());
Console.Write(executeFunctionMysql());
Console.Read();
}
}
}
mycat1.5配置如下
(1)、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://org.opencloudb/">
<system>
<property name="defaultSqlParser">druidparser</property>
<property name="useCompression">1</property>
<property name="processorBufferChunk">40960</property>
<property name="processors">32</property>
<property name="processorExecutor">32</property>
<property name="maxStringLiteralLength">65535</property>
<property name="sequnceHandlerType">0</property>
<property name="backSocketNoDelay">1</property>
<property name="frontSocketNoDelay">1</property>
<property name="idleTimeout">300000</property>
<property name="frontWriteQueueSize">4096</property>
<!-- <property name="useCompression">1</property>--> <!--1为开启mysql压缩协议-->
<!-- <property name="processorBufferChunk">40960</property> -->
<!--
<property name="processors">1</property>
<property name="processorExecutor">32</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="mutiNodeLimitType">1</property> 0:开启小数量级(默认) ;1:开启亿级数据排序
<property name="mutiNodePatchSize">100</property> 亿级数量排序批量
<property name="processors">32</property> <property name="processorExecutor">32</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> -->
</system>
<user name="sa">
<property name="password">jdd</property>
<property name="schemas">DataCenter_Odds</property>
</user>
<!-- <cluster> <node name="cobar1"> <property name="host">127.0.0.1</property>
<property name="weight">1</property> </node> </cluster> -->
<!-- <quarantine> <host name="1.2.3.4"> <property name="user">test</property>
</host> </quarantine> -->
</mycat:server>
(2)、schema.xml配置
<?xml version="1.0"?>
<!DOCTYPE mycat:schema SYSTEM "schema.dtd">
<mycat:schema xmlns:mycat="http://org.opencloudb/">
<schema name="DataCenter_Odds" checkSQLschema="false" sqlMaxLimit="100">
<table name="T_TEST1_1" dataNode="dn1"/>
<table name="T_TEST1" dataNode="dn1,dn2" rule="mod-long"/>
</schema>
<dataNode name="dn1" dataHost="localhost1" database="DataCenter_Odds" />
<dataNode name="dn2" dataHost="localhost2" database="DataCenter_Odds" />
<dataHost name="localhost1" maxCon="1000" minCon="1" balance="1" writeType="0" dbType="sqlserver" dbDriver="jdbc">
<heartbeat></heartbeat>
<connectionInitSql></connectionInitSql>
<writeHost host="hostM1" url="jdbc:sqlserver://10.10.97.232:1433" user="sa" password="123456">
<readHost host="hostS1" url="jdbc:sqlserver://10.10.97.232:1433" user="sa" password="123456"></readHost>
</writeHost>
</dataHost>
<dataHost name="localhost2" maxCon="1000" minCon="1" balance="1" writeType="0" dbType="sqlserver" dbDriver="jdbc">
<heartbeat></heartbeat>
<connectionInitSql></connectionInitSql>
<writeHost host="hostM2" url="jdbc:sqlserver://10.10.97.232:1433" user="sa" password="123456">
<readHost host="hostS2" url="jdbc:sqlserver://10.10.97.231:1433" user="sa" password="123456"></readHost>
</writeHost>
</dataHost>
</mycat:schema>
(3)、wrapper配置
#********************************************************************
# Wrapper Properties
#********************************************************************
# Java Application
wrapper.java.command=java
wrapper.working.dir=..
# Java Main class. This class must implement the WrapperListener interface
# or guarantee that the WrapperManager class is initialized. Helper
# classes are provided to do this for you. See the Integration section
# of the documentation for details.
wrapper.java.mainclass=org.tanukisoftware.wrapper.WrapperSimpleApp
set.default.REPO_DIR=lib
set.APP_BASE=.
# Java Classpath (include wrapper.jar) Add class path elements as
# needed starting from 1
wrapper.java.classpath.1=lib/wrapper.jar
wrapper.java.classpath.2=conf
wrapper.java.classpath.3=%REPO_DIR%/*
# Java Library Path (location of Wrapper.DLL or libwrapper.so)
wrapper.java.library.path.1=lib
# Java Additional Parameters
#wrapper.java.additional.1=
wrapper.java.additional.1=-DMYCAT_HOME=.
wrapper.java.additional.2=-server
wrapper.java.additional.3=-XX:MaxPermSize=512M
wrapper.java.additional.4=-XX:+AggressiveOpts
wrapper.java.additional.5=-XX:MaxDirectMemorySize=2G
wrapper.java.additional.6=-Dcom.sun.management.jmxremote
wrapper.java.additional.7=-Dcom.sun.management.jmxremote.port=1984
wrapper.java.additional.8=-Dcom.sun.management.jmxremote.authenticate=false
wrapper.java.additional.9=-Dcom.sun.management.jmxremote.ssl=false
wrapper.java.additional.10=-Xmx1G
wrapper.java.additional.11=-Xms1G
# Initial Java Heap Size (in MB)
#wrapper.java.initmemory=3
wrapper.java.initmemory=512
# Maximum Java Heap Size (in MB)
#wrapper.java.maxmemory=64
wrapper.java.maxmemory=512
# Application parameters. Add parameters as needed starting from 1
wrapper.app.parameter.1=org.opencloudb.MycatStartup
wrapper.app.parameter.2=start
#********************************************************************
# Wrapper Logging Properties
#********************************************************************
# Format of output for the console. (See docs for formats)
wrapper.console.format=PM
# Log Level for console output. (See docs for log levels)
wrapper.console.loglevel=INFO
# Log file to use for wrapper output logging.
wrapper.logfile=logs/wrapper.log
# Format of output for the log file. (See docs for formats)
wrapper.logfile.format=LPTM
# Log Level for log file output. (See docs for log levels)
wrapper.logfile.loglevel=INFO
# Maximum size that the log file will be allowed to grow to before
# the log is rolled. Size is specified in bytes. The default value
# of 0, disables log rolling. May abbreviate with the 'k' (kb) or
# 'm' (mb) suffix. For example: 10m = 10 megabytes.
wrapper.logfile.maxsize=0
# Maximum number of rolled log files which will be allowed before old
# files are deleted. The default value of 0 implies no limit.
wrapper.logfile.maxfiles=0
# Log Level for sys/event log output. (See docs for log levels)
wrapper.syslog.loglevel=NONE
#********************************************************************
# Wrapper Windows Properties
#********************************************************************
# Title to use when running as a console
wrapper.console.title=Mycat-server
#********************************************************************
# Wrapper Windows NT/2000/XP Service Properties
#********************************************************************
# WARNING - Do not modify any of these properties when an application
# using this configuration file has been installed as a service.
# Please uninstall the service before modifying this section. The
# service can then be reinstalled.
# Name of the service
wrapper.ntservice.name=mycat
# Display name of the service
wrapper.ntservice.displayname=Mycat-server
# Description of the service
wrapper.ntservice.description=The project of Mycat-server
# Service dependencies. Add dependencies as needed starting from 1
wrapper.ntservice.dependency.1=
# Mode in which the service is installed. AUTO_START or DEMAND_START
wrapper.ntservice.starttype=AUTO_START
# Allow the service to interact with the desktop.
wrapper.ntservice.interactive=false
wrapper.ping.timeout=120
configuration.directory.in.classpath.first=conf
(4)、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://org.opencloudb/">
<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>age</columns>
<algorithm>mod-long</algorithm>
</rule>
</tableRule>
<tableRule name="sharding-by-murmur">
<rule>
<columns>id</columns>
<algorithm>murmur</algorithm>
</rule>
</tableRule>
<tableRule name="sharding-by-month">
<rule>
<columns>create_date</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="org.opencloudb.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="hash-int"
class="org.opencloudb.route.function.PartitionByFileMap">
<property name="mapFile">partition-hash-int.txt</property>
</function>
<function name="rang-long"
class="org.opencloudb.route.function.AutoPartitionByLong">
<property name="mapFile">autopartition-long.txt</property>
</function>
<function name="mod-long" class="org.opencloudb.route.function.PartitionByMod">
<!-- how many data nodes -->
<property name="count">2</property>
</function>
<function name="func1" class="org.opencloudb.route.function.PartitionByLong">
<property name="partitionCount">8</property>
<property name="partitionLength">128</property>
</function>
<function name="latestMonth"
class="org.opencloudb.route.function.LatestMonthPartion">
<property name="splitOneDay">24</property>
</function>
<function name="partbymonth"
class="org.opencloudb.route.function.PartitionByMonth">
<property name="dateFormat">yyyy-MM-dd</property>
<property name="sBeginDate">2015-01-01</property>
</function>
<function name="rang-mod" class="org.opencloudb.route.function.PartitionByRangeMod">
<property name="mapFile">partition-range-mod.txt</property>
</function>
<function name="jump-consistent-hash" class="org.opencloudb.route.function.PartitionByJumpConsistentHash">
<property name="totalBuckets">3</property>
</function>
</mycat:rule>
通过以上的操作 即可完成mycat的相关配置
备注:在使用mycat的时候 首先要知道 mycat是对mysql的封装 所以客队要以访问mysql的方式连接
同时需要注意不同的sql之间的不兼容问题
相关推荐
2. **conf** 目录:存放MyCat的配置文件,如`schema.xml`(定义数据节点和表的分片策略)、`server.xml`(服务器配置)、`rule.xml`(分片规则)、`sys.properties`(系统配置)等。 3. **lib** 目录:包含运行MyCat...
5. **测试连接**:通过MySQL客户端或其他工具连接MyCat服务器,验证是否可以正常通信和执行SQL操作。 6. **监控与优化**:安装后,需要定期监控MyCat的运行状态,包括CPU、内存使用情况,以及日志中的错误信息,...
3. 连接测试:通过MySQL客户端连接mycat2,验证服务是否正常运行,可以执行简单的SQL查询来检查。 4. 应用集成:将mycat2作为数据库中间件接入到现有的应用系统中,修改数据库连接配置指向mycat2。 四、性能优化 ...
在实际应用中,Mycat-server处理来自应用的SQL请求,根据配置进行数据分片和路由,而Mycat-web则提供了一种友好的方式来管理和监控Mycat-server,确保系统的稳定运行。在大数据时代,这种架构对于处理海量数据和高...
它基于Java编写,能够支持多种数据库系统,如MySQL、Oracle、DB2、SQL Server和PostgreSQL,这使得它具有高度的兼容性和灵活性。Mycat的核心功能包括数据分片、读写分离以及数据库集群管理,这些特性有助于提升系统...
- **配置文件**:主要配置文件包括 `server.xml`、`schema.xml` 和 `dataNode.xml`,它们定义了 Mycat 服务器的基本设置、数据库分片规则和数据节点信息。 - **启动与停止**:通过执行 `bin/mysqld.sh start` 启动...
8. **支持多种数据库**:不仅限于MySQL,还兼容Oracle、SQL Server等多种数据库。 Mycat在实际应用中,常用于电商、金融、物联网等领域,处理大规模的在线交易和数据分析。对于开发者而言,理解和掌握Mycat的配置与...
Mycat支持多种数据库,如MySQL、SQL Server等,通过JDBC连接数据源。在运行时,Mycat会根据用户发送的SQL语句,结合配置信息,进行智能解析和路由,将请求分发到合适的数据节点上执行,再将结果合并后返回给客户端。...
Mycat不仅支持MySQL,还支持PostgreSQL、SQLServer等多类型数据库,具备良好的兼容性和扩展性。 1. **Mycat架构** Mycat由Server、Frontend Connector、Router、Schema、DataNode、Sequence等组件构成。Server负责...
在本文中,我们将详细探讨最新版的Mycat——Mycat-server-1.6.7.5-release-20200410174409在Windows操作系统上的安装、配置和使用。 1. **下载与解压** 首先,你需要从官方网站或可信的源获取`windows Mycat-...
总的来说,Mycat作为一款强大的分布式数据库中间件,通过合理的配置和使用,可以在CentOS7这样的Linux系统中搭建出高效稳定的数据库集群,满足大规模数据处理的需求。同时,对于开发者来说,理解Mycat的工作原理和...
MyCAT 是一个彻底开源的,面向企业应用开发的“大数据库集群” 支持事务、ACID、可以替代Mysql的加强版数据库, 一个可以视为“Mysql”集群的企业级数据库,用来替代昂贵的Oracle集群,一个融合内存缓存技术、Nosql...
MySQL中间件Mycat是为了解决大数据场景下的数据库扩展性问题而设计的,它作为一个分布式数据库系统,能够实现MySQL的读写分离以及分库分表功能。在本压缩包中,我们获得了Mycat 1.6.7.5的Windows版本,这是一款专为...
6. **测试连接**:使用MySQL客户端或者其他支持JDBC的应用,尝试连接到Mycat,验证其是否能正常转发SQL请求到后端的数据节点。 7. **监控与优化**:Mycat提供了丰富的日志功能,包括控制台输出、日志文件等,便于...
此外,Mycat支持多种数据库类型,如MySQL、SQL Server等,具备良好的兼容性。 压缩包中的"mycat-server-1.6-RELEASE-20161028204710-win.tar.gz"文件可能是Mycat的Linux版本,尽管标题表明是Windows版本,这可能是...
Mycat发展到目前版本,已经不在是一个单纯的MySQL代理了,它的后端可以支持MySQL、SQL Server、Oracle、DB2、PostgreSQL等主流数据库,也支持MongoDB这种新型NOSQL方式的存储,未来还会支持更多类型的存储。...
在本案例中,"mycat-server-1.6"指的是MyCat的一个特定版本,即1.6版,这通常包含了MyCat服务器的所有必要组件和配置文件,适用于Windows操作系统。 MyCat的核心功能可以分为以下几个方面: 1. **数据分片**:...
【Mycat-server-win】是专为Windows操作系统设计的一款中间件,它主要的功能是对MySQL数据库进行分库分表以及实现读写分离,从而提升数据库系统的性能和可扩展性。Mycat作为开源的数据库中间件解决方案,已经在许多...
在本案例中,我们将探讨如何在Mycat 1.6环境下操作SQLServer数据库,实现数据的高效管理和处理。 首先,我们需要理解Mycat的核心功能。Mycat通过将大数据量的表进行逻辑分片,使得单表的数据量得到控制,从而提高...
MySQL中间件Mycat是为了解决大数据场景下的数据库扩展性问题而设计的,它作为一个开源的分布式数据库系统,能够实现MySQL的读写分离、分库分表等功能,从而提高数据库系统的性能和可扩展性。在本文中,我们将深入...