nginx负载均衡+数据库主从复制+sharding实现数据库主从分离

前言

最近为公司服务器配置主备服务器,按大牛的建议配置了这么一套标准的部署。

nginx负载均衡

直接上主要的配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
upstream xxx.device {
server ip:port;
server ip:port;
}
location /device/ {
proxy_pass http://xxx.device/;
##proxy_redirect default;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS, PUT, DELETE';
add_header Access-Control-Allow-Headers '*';
if ($request_method = 'OPTIONS') {

#支持put和delete请求
return 200;
}
}

坑点:

upstream节点下的server的配置不能直接使用ip

而应该是ip+port才能生效

后期可以直接去使用阿里云的负载均衡 ,前提是量够大。

https://help.aliyun.com/document_detail/129367.htm?spm=a2c4g.11186623.2.10.656857c43QenNV#task-1597516

引入其服务可以解决程序的单点故障。

数据库主从复制

作用很容易理解:从库去主库复制数据,因为读写分离主库作为写入的库,从库只提供提取,为了数据同步这个是一定要弄得。

这个mysql已经提供,所以只需要跟着文档跟着配置就行.

这里我直接放参考的博客了

https://zhuanlan.zhihu.com/p/138420773

sharding实现读写分离

sharding是一个比较新的数据库中间件。

选择原因是更新频率高、社区完善、负责人不傻x。

官网https://shardingsphere.apache.org/index_zh.html

坑点:

文档更新不及时、更新频率太快了。。

原本是使用4.0的版本配合文档接入,配置很简单,但是一上服务器容器直接异常,且无法logs 查看日志。

左右摆弄终于是配置5.0ok了,一定要去注意pom和properties文件的配置,他们4.0和5.0properties的配置改动很大。。而且蛋疼的是官网提供的最新文档还是有问题跑不起来,有些经过验证发现是4.0过时的配置。。官方demo也是可阅读性。。。一言难尽。。

所以对这个有兴趣想敲个demo的话,尽量直接使用我的配置..

pom

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.apache.shardingsphere</groupId>-->
<artifactId>shardingsphere-jdbc-core-spring-boot-starter</artifactId>
<version>5.0.0-alpha</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>

properties

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
##数据库配置
spring.shardingsphere.datasource.names=master,slave

spring.shardingsphere.datasource.common.type=com.zaxxer.hikari.HikariDataSource
spring.shardingsphere.datasource.common.driver-class-name=com.mysql.jdbc.Driver
spring.shardingsphere.datasource.common.username=root
spring.shardingsphere.datasource.common.password=root
spring.shardingsphere.datasource.master.jdbc-url=
spring.shardingsphere.datasource.slave.jdbc-url=


spring.shardingsphere.rules.replica-query.data-sources.zykj.name=zykj
spring.shardingsphere.rules.replica-query.load-balancers.round-robin.type=ROUND_ROBIN
spring.shardingsphere.rules.replica-query.data-sources.zykj.primary-data-source-name=master
spring.shardingsphere.rules.replica-query.data-sources.zykj.replica-data-source-names=slave
spring.shardingsphere.rules.replica-query.data-sources.zykj.load-balancer-name=round_robin
#必须得配,不配报错。虽然官方文档写负载均衡没有其他属性配置
spring.shardingsphere.rules.replica-query.load-balancers.round-robin.props.default=0
# 显示SQL
spring.shardingsphere.props.sql.show=true
# 解决异常
spring.main.allow-bean-definition-overriding=true

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!