远行的心 发表于 2019-1-2 09:44:23

Haproxy+多台MySQL从服务器(Slave) 实现负载均衡

  本系统采用MySQL一主多从模式设计,即1台 MySQL“主”服务器(Master)+多台“从”服务器(Slave),“从”服务器之间通过Haproxy进行负载均衡,对外只提供一个访问IP,当程序需要访问多台"从"服务器时,只需要访问Haproxy,再由Haproxy将请求分发到各个数据库节点。
  

  我们的程序可以有俩个数据源(DataSourceA,DataSourceB),一个(DataSourceA)直接连接主库,另外一个(DataSourceB)连接Haproxy,当需要写入操作时可以使用DataSourceA,读取时使用DataSourceB。
  

  设计图如下:
http://img.blog.csdn.net/20150908163713641?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center

  

  看到这里大家可能会有一个疑问,这个问题就是主从数据库之间数据同步延时的问题!
  因为大多数使用MySQL主从同步数据都是异步的,也就是说当主库的数据发生变化时并不能立即的更新从库,这么做的目的也是为了更好的性能,那么设想一下,当用户新增一条记录后立刻去从库查询,可能并不能查到刚刚新增的数据,这岂不是很脑裂的问题~~~。
  

  然而实际情况并不应该是这样的,我们也不应该这样去设计程序,我们就拿一个类似于CSND博客管理的系统来说,假设一个“博客系统”只有俩部分, 一部分是博客管理后台,用户可以在后台新增,编辑,删除博客。另一部分是门户网站,负责展示所有用户的博客信息,相对于这样一个系统来说, 后台管理模块对数据库的操作压力不是很大,相反门户网站读取博客信息对数据库的压力很大,这也式一般互联网产品的特点,而且最重要的一点是系统可以接受主从同步数据带来的延迟,也就是说当用户在后台新增一条博客时,前台门户网站并不能立即查询到这条信息。一般都是再过一段时间后才会出现在首页,因为大多数系统都有缓存设置,这样正好给主从同步延迟带来时间。
  

  接着说上面的问题,有的同学可能会有这样的疑问,就是后台用户在新增一条记录后,一般都是立即查询返回博客列表,按照上面说的岂不是查询不到~~~,我觉得这个问题可以这么解决:
  1、后台用户在进行 新增,查询,编辑,删除等操作时直接连接主库,这样无论什么操作都是实时的,因为后台操作对数据库的压力不是很大,所以读写全部连接主库应该没什么问题!
  2、门户网站查询博客列表时从 “从库集群中查询“,通过负载均衡技术,解决了扩展性,高可用性等问题,同时门户网站首页也不需要实时查询主库中的数据,因为网站本身一般都有缓存,也不是实时的。
  

  上面的架构设计只是抛砖引玉,大家有什么好想法也可以相互交流~
  本文重点介绍的内容有二点:
  1、如何使用Haproxy给MySQL做负载均衡,提供相关的配置说明,健康检查等等。
  2、当程序通过连接Haproxy代理之后,如何解决程序中连接池长连接失效的问题。
  

  下面介绍如何安装配置Haproxy~
  1、首先进行负载均衡配置。
  假设两台MySQL(slave)从服务器A:192.168.1.191:3306      B:192.168.1.192:3306。
  

  首先在linxu上安装Haproxy,安装过程略。。。。。。
  安装完毕后打开配置文件在/etc/haproxy/ haproxy.cfg,配置文件的路径可能不用,别告诉我找不到~~~!
  
   view plain copy print?

[*]  global
[*]  maxconn 4096
[*]  daemon
[*]  chroot      /var/lib/haproxy
[*]  pidfile   /var/run/haproxy.pid
[*]  #debug
[*]  #quiet
[*]  user haproxy
[*]  group haproxy
[*]
[*]  defaults
[*]  log   global
[*]  mode    http
[*]  optionhttplog
[*]  optiondontlognull
[*]  log 127.0.0.1 local0
[*]  retries 3
[*]  option redispatch
[*]  maxconn 2000
[*]  #contimeout      5000
[*]  #clitimeout      50000
[*]  #srvtimeout      50000
[*]  timeout http-request    10s
[*]  timeout queue         1m
[*]  timeout connect         10s
[*]  timeout client          1m
[*]  timeout server          1m
[*]  timeout http-keep-alive 10s
[*]  timeout check         10s
[*]
[*]  listenadmin_stats 0.0.0.0:8888
[*]  mode      http
[*]  stats uri   /dbs
[*]  stats realm   Global\ statistics
[*]  stats authadmin:admin
[*]
[*]  listenproxy-mysql 0.0.0.0:23306
[*]  mode tcp
[*]  balance roundrobin
[*]  option tcplog
[*]  option mysql-check user haproxy #在mysql中创建无任何权限用户haproxy,且无密码
[*]  server MySQL1 192.168.1.191:3306 check weight 1 maxconn 2000
[*]  server MySQL2 192.168.1.192:3306 check weight 1 maxconn 2000
[*]  option tcpka
  

  
   view plain copy print?

[*]  listenadmin_stats 0.0.0.0:8888 这个配置是监控页面,绑定到本机8888端口,账号admin,密码admin
http://static.blog.csdn.net/images/save_snippets_01.png
listenadmin_stats 0.0.0.0:8888 这个配置是监控页面,绑定到本机8888端口,账号admin,密码admin  可以通过web的方式查看所有MySQL节点的使用情况, http://你的IP:8888/dbs 即可登录监控后台。
  如下图:
  http://img.blog.csdn.net/20150828161453678?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center

  

  
   view plain copy print?

[*]  listenproxy-mysql 0.0.0.0:23306
[*]  mode tcp
[*]  balance roundrobin
[*]  option tcplog
[*]  option mysql-check user haproxy #在mysql中创建无任何权限用户haproxy,且无密码
[*]  server MySQL1 192.168.1.191:3306 check weight 1 maxconn 2000
[*]  server MySQL2 192.168.1.192:3306 check weight 1 maxconn 2000
[*]  option tcpka
http://static.blog.csdn.net/images/save_snippets.png
listenproxy-mysql 0.0.0.0:23306
      mode tcp
      balance roundrobin
      option tcplog
      option mysql-check user haproxy #在mysql中创建无任何权限用户haproxy,且无密码
      server MySQL1 192.168.1.191:3306 check weight 1 maxconn 2000
      server MySQL2 192.168.1.192:3306 check weight 1 maxconn 2000
      option tcpka   view plain copy print?

[*]  proxy-mysql 0.0.0.0:23306 代理的端口。我们程序连接从库集群时就访问这个端口。
http://static.blog.csdn.net/images/save_snippets_01.png
proxy-mysql 0.0.0.0:23306 代理的端口。我们程序连接从库集群时就访问这个端口。   view plain copy print?

[*]  balance roundrobin 负载均衡方式,有很多种,可以去Google。
http://static.blog.csdn.net/images/save_snippets_01.png
balance roundrobin 负载均衡方式,有很多种,可以去Google。   view plain copy print?

[*]  option mysql-check user haproxy 这里是配置健康检查的,也是haproxy自带的功能,需要在mysql中创建无任何权限用户haproxy,且无密码
http://static.blog.csdn.net/images/save_snippets.png
option mysql-check user haproxy 这里是配置健康检查的,也是haproxy自带的功能,需要在mysql中创建无任何权限用户haproxy,且无密码   view plain copy print?

[*]  server MySQL1 192.168.1.191:3306 check weight 1 maxconn 2000 配置MySQL从库节点,有多少配置多少就行了。
http://static.blog.csdn.net/images/save_snippets_01.png
server MySQL1 192.168.1.191:3306 check weight 1 maxconn 2000 配置MySQL从库节点,有多少配置多少就行了。  

  

  有的同学可能不知道如何在MySQL中创建用户,这里也给你写好了。
  用户名为haproxy 且无密码(重要) 否则haproxy无法检测MySQL状态。

  CREATE USER 'haproxy'@'%' IDENTIFIED BY '';
  

  配置完成后启动代理 service haproxy start如果用过yum方式安装,应该就能启动了,如果是其它方式安装,可能启动方式不同,需要编写脚本启动,应该不难自己研究一下~~~
  

  然后让我们写个demo测试一下代理是否配置成功了没!
  

   view plain copy print?

[*]  public static void main(String[] args) throws Exception {
[*]
[*]
[*]  Class.forName("com.mysql.jdbc.Driver");
[*]  Connection conn = DriverManager.getConnection("jdbc:mysql://你的IP:23306/template?useUnicode=true", "root", "sql2008");
[*]
[*]  for (int i = 0; i < 100; i++) {
[*]  PreparedStatement pr = null;
[*]  ResultSet res = null;
[*]  try {
[*]  pr = conn.prepareStatement("select count(*) from sys_user");
[*]  res = pr.executeQuery();
[*]  if(res.next()) {
[*]  System.out.println(new Date().toLocaleString() + "->" + res.getInt(1));
[*]  }
[*]  } catch (Exception e) {
[*]  e.printStackTrace();
[*]  res.close();
[*]  pr.close();
[*]  }
[*]
[*]  Thread.sleep(25000);
[*]  }
[*]
[*]  conn.close();
[*]  }
http://static.blog.csdn.net/images/save_snippets.png
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://你的IP:23306/template?useUnicode=true", "root", "sql2008");
for (int i = 0; i < 100; i++) {
PreparedStatement pr = null;
ResultSet res = null;
try {
pr = conn.prepareStatement("select count(*) from sys_user");
res = pr.executeQuery();
if(res.next()) {
System.out.println(new Date().toLocaleString() + "->" + res.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
res.close();
pr.close();
}
Thread.sleep(25000);
}
conn.close();
}  

  

  输出结果如下:可以看到代理MySQL成功了,这时你可以随机关掉一个MySQL节点的服务,程序依然能够正常的执行,说明负载均衡也成功了。
  
   view plain copy print?

[*]  2015-8-28 10:09:27->7
[*]  2015-8-28 10:09:52->7
[*]  2015-8-28 10:10:17->7
[*]  2015-8-28 10:10:42->7
[*]  2015-8-28 10:11:07->7
http://static.blog.csdn.net/images/save_snippets.png
2015-8-28 10:09:27->7
2015-8-28 10:09:52->7
2015-8-28 10:10:17->7
2015-8-28 10:10:42->7
2015-8-28 10:11:07->7  

  

  小小的激动有没有~有没有~。于是乎我们就把程序中数据源的配置改造一下,让它连接haproxy即可。
   .
  是不是以为大功告成了,如果你就这样配置的话,等程序运行起来它就会给你一个大大的surprisehttp://static.blog.csdn.net/xheditor/xheditor_emot/default/laugh.gif
  其实这里面是有坑的~~~~,且听我细细道来。
  

  一般的情况下,我相信大家在直接连接MySQL的时候几乎都用到了连接池。
  以我的配置为例:
  
   view plain copy print?

[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  
[*]  lt;/bean>
http://static.blog.csdn.net/images/save_snippets.png
   












  
其它的参数这里不解释,大家可以查询C3P0配置信息,网上很多。
  

  这里只说一个:
   view plain copy print?

[*]  idleConnectionTestPeriod=30 这个参数是配置连接池 每隔多少时间去检查池内链接的有效性,单位秒。
http://static.blog.csdn.net/images/save_snippets_01.png
idleConnectionTestPeriod=30 这个参数是配置连接池 每隔多少时间去检查池内链接的有效性,单位秒。   view plain copy print?

[*]  我这里设置成30秒,那么C3P0会每隔30秒 把连接池内所有的空闲连接拿出来挨个发一个测试SQL语句,已确定这个链接的有效性。
http://static.blog.csdn.net/images/save_snippets_01.png
我这里设置成30秒,那么C3P0会每隔30秒 把连接池内所有的空闲连接拿出来挨个发一个测试SQL语句,已确定这个链接的有效性。  

  以前我们的数据源是直接连接MySQL数据库的,在正常的情况下MySQL是不会断开这个链接的。
  但是我们现在连接的是haproxy,也就是说我们程序的连接(Connection)是与haproxy建立的,这里的坑在于这个连接是会被haproxy断掉的,这样的话你连接池内的链接就变成了无效链接,在下次需要查询数据库时还需要重新创建连接,而且程序由于拿到的连接是无效链接,还有可能报错。
  

  那么haproxy与我们程序之间的连接超时时间在哪设置呢?
  
   view plain copy print?

[*]  timeout client          1m#这个参数配置程序与haproxy的链接超时时间
[*]  timeout server          1m#这个参haproxy与mysql链接超时时间
http://static.blog.csdn.net/images/save_snippets.png
      timeout client          1m#这个参数配置程序与haproxy的链接超时时间
      timeout server          1m#这个参haproxy与mysql链接超时时间  这里的超时时间不是指连接过程的超时时间,而是指连接上以后,多少时间内没有心跳,操作这个时间就认为超时,然后断开连接。
  

  写的可能有些啰嗦,我们看个例子开说明一下:
  
   view plain copy print?

[*]  public static void main(String[] args) throws Exception {
[*]
[*]
[*]  Class.forName("com.mysql.jdbc.Driver");
[*]  Connection conn = DriverManager.getConnection("jdbc:mysql://你的IP:23306/template?useUnicode=true", "root", "sql2008");
[*]
[*]  for (int i = 0; i < 100; i++) {
[*]  PreparedStatement pr = null;
[*]  ResultSet res = null;
[*]  try {
[*]  pr = conn.prepareStatement("select count(*) from sys_user");
[*]  res = pr.executeQuery();
[*]  if(res.next()) {
[*]  System.out.println(new Date().toLocaleString() + "->" + res.getInt(1));
[*]  }
[*]  } catch (Exception e) {
[*]  e.printStackTrace();
[*]  res.close();
[*]  pr.close();
[*]  }
[*]
[*]  Thread.sleep(60000);
[*]  }
[*]
[*]  conn.close();
[*]  }
http://static.blog.csdn.net/images/save_snippets.png
public static void main(String[] args) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://你的IP:23306/template?useUnicode=true", "root", "sql2008");
for (int i = 0; i < 100; i++) {
PreparedStatement pr = null;
ResultSet res = null;
try {
pr = conn.prepareStatement("select count(*) from sys_user");
res = pr.executeQuery();
if(res.next()) {
System.out.println(new Date().toLocaleString() + "->" + res.getInt(1));
}
} catch (Exception e) {
e.printStackTrace();
res.close();
pr.close();
}
Thread.sleep(60000);
}
conn.close();
}  

  

  我上面配置的是 timeout client 1m ,也就是说客户端连接到haproxy后 1分钟之内没有数据请求即为超时,就会断掉链接:
  
   view plain copy print?

[*]  第一次查询没有问题:
http://static.blog.csdn.net/images/save_snippets_01.png
第一次查询没有问题:  Thread.sleep(60000); 我把间隔设置为60秒,第二次查询与第一次查询间隔60秒就会报错,因为超时了。
  


   view plain copy print?

[*]  那如果我把间隔改为 Thread.sleep(50000); 50秒,就不会报错。
http://static.blog.csdn.net/images/save_snippets_01.png
那如果我把间隔改为 Thread.sleep(50000); 50秒,就不会报错。
  

  

  结论就是
   view plain copy print?

[*]  idleConnectionTestPeriod 的时间一定要小于 timeout client的时间。这样C3P0会在Haproxy断掉链接之前发送一次“心跳”过去,保持链接的有效性。
http://static.blog.csdn.net/images/save_snippets.png
idleConnectionTestPeriod 的时间一定要小于 timeout client的时间。这样C3P0会在Haproxy断掉链接之前发送一次“心跳”过去,保持链接的有效性。   view plain copy print?

[*]  而且 timeout client与 timeout server 尽量保持一致,已达到最佳效果。
  




页: [1]
查看完整版本: Haproxy+多台MySQL从服务器(Slave) 实现负载均衡