动态切换数据库连接方案(动态切换数据库连接方案怎么设置)
引言
- 需求: 查询SQL Server数据库的时候可以根据实际情况分配服务器来提供服务,大大提高服务速度和优化性能,完成负载均衡。
- 方案:推荐从数据库服务端做集群
- 数据库服务器:
- 例如SQL Server数据库可以采用ICX 动态路由,所有的数据库客户都通过ICX访问数据库。
- SQL Server的Always On 故障转移群集
- Moebius for SQL server
- 数据库客户端:
- 使用nginx-upsync-module模块配置Nginx以实现sql server 数据库负载均衡
- 使用数据库时,先从数据库实例状态表查询可用的数据库连接信息
- 书写脚本,修改数据库连接信息,手动切换。
I 案例:手动切换数据库配置
存储数据库配置信息
基于spring.profiles.include属性加载不同的配置文件
配置方法:
- 若是properties文件:spring.profiles.include=dev1,dev2
配置spring.profiles.active=dev,
application-dev.properties中,配置spring.profiles.include=dev1,dev2。使用
application-dev.properties时自动就激活了dev1、dev2两个文件
控制台打印The following profiles are active:dev, dev1,dev2
- 若是yaml文件中
spring
profiles
include:
-dev1
-dev2
书写切换脚本
切换到15数据库
#!/bin/bash
sed -i 's/include: 18jdbc/include: 15jdbc/g'
/usr/local/bttomcat/tomcat9/webapps/xx/WEB-INF/classes/application-prod.yml
#-i选项会直接在文件上进行修改。
# 重启tomcat服务
/etc/rc.d/init.d/bttomcat9 stop && /etc/init.d/bttomcat9 start 2> /dev/null
切换到18数据库脚本touch 18jdbc.sh; chmod a+x 18jdbc.sh
#!/bin/bash
sed -i 's/include: 15jdbc/include: 18jdbc/g'
/usr/local/bttomcat/tomcat9/webapps/xx/WEB-INF/classes/application-prod.yml
#-i选项会直接在文件上进行修改。
# 重启tomcat服务
/etc/rc.d/init.d/bttomcat9 stop && /etc/init.d/bttomcat9 start 2> /dev/null
II 知识扩展
使用sed命令替换文件内容
将文件filename中所有出现的oldtext替换为newtext。
sed -i 's/old_text/new_text/g' filename
#-i选项会直接在文件上进行修改。
激活环境配置文件
命名规则遵循application-${profile}.properties,例如:
- 开发环境配置文件:application-dev.properties
- 测试环境配置文件:application-test.properties
- 生产环境配置文件:application-prod.properties
#激活的是开发环境配置文件
spring.profiles.active=dev
执行有参启动时,可以在命令中进行指定要选用的配置文件
java -jar xx.jar --spring.profiles.active=test