spring+spring mvc+mybatis 实现主从数据库配置
一、配置文件
1、jdbc.properties
master_driverUrl=jdbc:mysql://localhost:3306/shiro?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
master_username=root
master_password= slave_driverUrl=jdbc:mysql://localhost:3306/wechat?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true
slave_username=root
slave_password=
2、spring-mybatis.xml
<!-- 多数据源aop datasource -->
<context:component-scan base-package="com.wangzhixuan.commons.datasource" /> <!-- base dataSource -->
<bean name="baseDataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="initialSize" value="" />
<property name="maxActive" value="" />
<property name="minIdle" value="" />
<property name="maxWait" value="" />
<property name="validationQuery" value="SELECT 'x'" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="" />
<property name="minEvictableIdleTimeMillis" value="" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="" />
<property name="logAbandoned" value="true" />
<property name="filters" value="mergeStat" />
</bean> <!-- 主库 -->
<bean name="master-dataSource" parent="baseDataSource"
init-method="init">
<property name="url" value="${master_driverUrl}" />
<property name="username" value="${master_username}" />
<property name="password" value="${master_password}" />
</bean> <!-- 从库 -->
<bean name="slave-dataSource" parent="baseDataSource" init-method="init">
<property name="url" value="${slave_driverUrl}" />
<property name="username" value="${slave_username}" />
<property name="password" value="${slave_password}" />
</bean> <!--主从库选择 -->
<bean id="dynamicDataSource" class="com.wangzhixuan.commons.datasource.DynamicDataSource">
<property name="master" ref="master-dataSource" />
<property name="slaves">
<list>
<ref bean="slave-dataSource" />
</list>
</property>
</bean>
二、通用类
1.DataSourceAspect 切换到指定的数据源
package com.wangzhixuan.commons.datasource; import com.wangzhixuan.commons.annotation.DataSourceChange;
import com.wangzhixuan.commons.exception.DataSourceAspectException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component; /**
* 有{@link com.wangzhixuan.commons.annotation.DataSourceChange}注解的方法,调用时会切换到指定的数据源
*
* @author tanghd
*/
@Aspect
@Component
public class DataSourceAspect {
private static final Logger LOGGER = LoggerFactory.getLogger(DataSourceAspect.class); @Around("@annotation(dataSourceChange)")
public Object doAround(ProceedingJoinPoint pjp, DataSourceChange dataSourceChange) {
Object retVal = null;
boolean selectedDataSource = false;
try {
if (null != dataSourceChange) {
selectedDataSource = true;
if (dataSourceChange.slave()) {
DynamicDataSource.useSlave();
} else {
DynamicDataSource.useMaster();
}
}
retVal = pjp.proceed();
} catch (Throwable e) {
LOGGER.warn("数据源切换错误", e);
throw new DataSourceAspectException("数据源切换错误", e);
} finally {
if (selectedDataSource) {
DynamicDataSource.reset();
}
}
return retVal;
}
}
2.AbstractRoutingDataSource 配置主从数据源后,根据选择,返回对应的数据源
package com.wangzhixuan.commons.datasource; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import javax.sql.DataSource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong; /**
* 继承{@link org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource}
* 配置主从数据源后,根据选择,返回对应的数据源。多个从库的情况下,会平均的分配从库,用于负载均衡。
*
* @author tanghd
*/
public class DynamicDataSource extends AbstractRoutingDataSource { private static final Logger LOGGER = LoggerFactory.getLogger(DynamicDataSource.class); private DataSource master; // 主库,只允许有一个
private List<DataSource> slaves; // 从库,允许有多个
private AtomicLong slaveCount = new AtomicLong();
private int slaveSize = ; private Map<Object, Object> dataSources = new HashMap<Object, Object>(); private static final String DEFAULT = "master";
private static final String SLAVE = "slave"; private static final ThreadLocal<LinkedList<String>> datasourceHolder = new ThreadLocal<LinkedList<String>>() { @Override
protected LinkedList<String> initialValue() {
return new LinkedList<String>();
} }; /**
* 初始化
*/
@Override
public void afterPropertiesSet() {
if (null == master) {
throw new IllegalArgumentException("Property 'master' is required");
}
dataSources.put(DEFAULT, master);
if (null != slaves && slaves.size() > ) {
for (int i = ; i < slaves.size(); i++) {
dataSources.put(SLAVE + (i + ), slaves.get(i));
}
slaveSize = slaves.size();
}
this.setDefaultTargetDataSource(master);
this.setTargetDataSources(dataSources);
super.afterPropertiesSet();
} /**
* 选择使用主库,并把选择放到当前ThreadLocal的栈顶
*/
public static void useMaster() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("use datasource :" + datasourceHolder.get());
}
LinkedList<String> m = datasourceHolder.get();
m.offerFirst(DEFAULT);
} /**
* 选择使用从库,并把选择放到当前ThreadLocal的栈顶
*/
public static void useSlave() {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("use datasource :" + datasourceHolder.get());
}
LinkedList<String> m = datasourceHolder.get();
m.offerFirst(SLAVE);
} /**
* 重置当前栈
*/
public static void reset() {
LinkedList<String> m = datasourceHolder.get();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("reset datasource {}", m);
}
if (m.size() > ) {
m.poll();
}
} /**
* 如果是选择使用从库,且从库的数量大于1,则通过取模来控制从库的负载,
* 计算结果返回AbstractRoutingDataSource
*/
@Override
protected Object determineCurrentLookupKey() {
LinkedList<String> m = datasourceHolder.get();
String key = m.peekFirst() == null ? DEFAULT : m.peekFirst();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("currenty datasource :" + key);
}
if (null != key) {
if (DEFAULT.equals(key)) {
return key;
} else if (SLAVE.equals(key)) {
if (slaveSize > ) {// Slave loadBalance
long c = slaveCount.incrementAndGet();
c = c % slaveSize;
return SLAVE + (c + );
} else {
return SLAVE + "";
}
}
return null;
} else {
return null;
}
} public DataSource getMaster() {
return master;
} public List<DataSource> getSlaves() {
return slaves;
} public void setMaster(DataSource master) {
this.master = master;
} public void setSlaves(List<DataSource> slaves) {
this.slaves = slaves;
} }
3.DataSourceChange 主从数据源切换注解
package com.wangzhixuan.commons.annotation; import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceChange {
boolean slave() default false;
}
三、在服务层调用时加入数据源标识,DataSourceChange注解,设置数据源为从库(这里只写出了接口的实现,dao和mapper,请自行添加)
package com.wangzhixuan.service.impl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.wangzhixuan.commons.annotation.DataSourceChange;
import com.wangzhixuan.mapper.SlaveMapper;
import com.wangzhixuan.service.SlaveService; @Service
public class SlaveServiceImpl implements SlaveService { @Autowired
private SlaveMapper slaveMapper; @Override
@DataSourceChange(slave = true)
public Integer count() {
return slaveMapper.count();
} @Override
@DataSourceChange(slave = true)
public Integer count2() {
return slaveMapper.count2();
} }
四、测试类(这里是查询从库里的一张表的记录总数),将原来的主库切换到从库。
@Test
public void testFindAllShop() {
Integer count = slaveService.count();
//Integer count2 = slaveService.count2();
System.out.println("#######1:"+count);
}
需要注意的一点:
@DataSourceChange(slave = true)只对service(业务)层起作用。
如果在测试类@Test下加是无作用的
@Test
@DataSourceChange(slave = true)
public void testFindAllShop() {
Integer count = slaveService.count();
//Integer count2 = slaveService.count2();
System.out.println("#######1:"+count);
}
博客转自:https://www.cnblogs.com/aegisada/p/5699058.html
spring+spring mvc+mybatis 实现主从数据库配置的更多相关文章
- Unit03: Spring Web MVC简介 、 基于XML配置的MVC应用 、 基于注解配置的MVC应用
Unit03: Spring Web MVC简介 . 基于XML配置的MVC应用 . 基于注解配置的MVC应用 springmvc (1)springmvc是什么? 是一个mvc框架,用来简化基于mv ...
- Spring JDBC主从数据库配置
通过昨天学习的自定义配置注释的知识,探索了解一下web主从数据库的配置: 背景:主从数据库:主要是数据上的读写分离: 数据库的读写分离的好处? 1. 将读操作和写操作分离到不同的数据库上,避免主服务器 ...
- spring boot + druid + mybatis + atomikos 多数据源配置 并支持分布式事务
文章目录 一.综述 1.1 项目说明 1.2 项目结构 二.配置多数据源并支持分布式事务 2.1 导入基本依赖 2.2 在yml中配置多数据源信息 2.3 进行多数据源的配置 三.整合结果测试 3.1 ...
- 2018-01-08 学习随笔 SpirngBoot整合Mybatis进行主从数据库的动态切换,以及一些数据库层面和分布式事物的解决方案
先大概介绍一下主从数据库是什么?其实就是两个或N个数据库,一个或几个主负责写(当然也可以读),另一个或几个从只负责读.从数据库要记录主数据库的具体url以及BigLOG(二进制日志文件)的参数.原理就 ...
- CentOS7下Mysql5.7主从数据库配置
本文配置主从使用的操作系统是Centos7,数据库版本是mysql5.7. 准备好两台安装有mysql的机器(mysql安装教程链接) 主数据库配置 每个从数据库会使用一个MySQL账号来连接主数据库 ...
- CentOS 6.6 中 mysql_5.6 主从数据库配置
[mysql5.6 主从复制] 1.配置主从节点的服务配置文件 1.1.配置master节点 [mysqld] binlog-format=row log-bin=master-bin log-sla ...
- MySQL主从数据库配置与原理
1.为什么要搭建主从数据库 (1)通过增加从库实现读写分离,提高系统负载能力 (2)将从库作为数据库备份库,实现数据热备份,为数据恢复提供机会 (3)根据业务将不同服务部署在不同机器同时又共享相同的数 ...
- spring mvc+mybatis+sql server简单配置
context.xml配置文件 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns=&qu ...
- MAVEN构建Spring +Spring mvc + Mybatis 项目(Maven配置部分(workshop))
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...
随机推荐
- 9.5、Libgdx加速度计
(官网:www.libgdx.cn) 加速度计可以让设备通过三个坐标轴检测加速度.通过加速度可以检测设备的方向. 加速度的单位是米每秒的平方.如果一个坐标轴指向地心,加速度大概是-10米每秒的平方.如 ...
- Asp.Net中使用JQueryEasyUI--善良公社项目
jQuery UI 是以 jQuery 为基础的开源 JavaScript 网页用户界面代码库.包含底层用户交互.动画.特效和可更换主题的可视控件.我们可以直接用它来构建具有很好交互性的web应用程序 ...
- 大多数时候是软件的Bug,但是... 有时候的确是硬件的问题!
在我们性能最好的服务器中,有一台是从之前的64位测试项目中遗留下来的.那台机器配有皓龙250双核处理器,内存有8 GB.服役了一年之后,那种配置仍然是相当不错的.它还有贴心的升级方案可选:它的泰安Th ...
- js中return false,return,return true的用法及区别
首先return作为返回关键字,他有以下两种返回方式 1.返回控制与函数结果 语法为:return 表达式; 语句结束函数执行,返回调用函数,而且把表达式的值作为函数的结果 2.返回控制无函数结果 语 ...
- Iterm2安装Zsh + Oh My Zsh+Solarized
安装Oh My Zsh curl -L https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh | sh 安装Zsh ...
- Ubuntu15.04 + Matlab2014a + MatConvNet install and compile
MatConvNet is a MATLAB toolbox implementingConvolutional NeuralNetworks (CNNs) for computer vision a ...
- 开发资源库(repositiory)
1.. 52研发网MTK软件 2.一流研发 3. android+MTK/华为的源代码及资料库(CryToCry96) 点击打开链接 4.android+MTK/华为/联想的源代码及资料库(lucka ...
- STL - set和multiset
set/multiset的简介 set是一个集合容器,其中所包含的元素是唯一的,集合中的元素按一定的顺序排列.元素插入过程是按排序规则插入,所以不能指定插入位置. set采用红黑树变体的数据结构实现, ...
- STL - queue(队列)
Queue简介 queue是队列容器,是一种"先进先出"的容器. queue是简单地装饰deque容器而成为另外的一种容器. #include <queue> queu ...
- Android不同系统版本依然能调用到正确的API方法Demo——Service调用startForeground举例
private static final Class<?>[] mSetForegroundSignature = new Class[] { boolean.class}; privat ...