Spring 数据源配置三:多数据源
在上一节中,我们讲述了多数据的情况:
1. 数据源不同(数据库厂商不同, 业务范围不同, 业务数据不同)
2. SQL mapper 文件不同,
3. mybatis + 数据方言不同
即最为简单的多数据, 将多个数据源叠加在一起,不同service---》dao--->sessionFactory;
如果上述的所有条件都相同,仅仅是数据的的多个拷贝情况,想做主备(读写分离),那我们当然可以用2套复制的代码和配置,但是显然不是最佳的实现方式。
这里,我们就讲解一下多数据源的读写分离,怎么实现。
首先,我们从读写分离的入口来看, 读read (对应JAVA/ getXXX, queryXXX), 写write(对应updateXXX, insertXXX), 如果能在这些方法执行时,自动切换到只读数据库/只写数据,那么就可以实现读写分离, 那我们自然可以想到spring 的AOP, 并以annotation的方式实现。
具体实现步骤如下:
1. 实现自定义的数据源注解: @DataSource("read") / @DataSource("write")
package com.robin.it.ds; import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.ElementType;
/**
* RUNTIME
* 编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
* @author Robin.yi
*
*/ @Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DataSource {
String value();
}
2. 实现一个数据库选择器ChooseDataSource
package com.robin.it.ds; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class ChooseDataSource extends AbstractRoutingDataSource { @Override
protected Object determineCurrentLookupKey() {
return HandleDataSource.getDataSource();
} } ============
package com.robin.it.ds; public class HandleDataSource { public static final ThreadLocal<String> holder = new ThreadLocal<String>(); public static void putDataSource(String datasource) {
holder.set(datasource);
} public static String getDataSource() {
return holder.get();
}
}
3. 实现AOP 的的数据拦截,切换功能
package com.robin.it.ds; import java.lang.reflect.Method; import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
//@Aspect
//@Component
public class DataSourceAspect {
//@Pointcut("execution(* com.apc.cms.service.*.*(..))")
public void pointCut(){}; // @Before(value = "pointCut()")
public void before(JoinPoint point)
{
Object target = point.getTarget();
System.out.println(target.toString());
String method = point.getSignature().getName();
System.out.println(method);
Class<?>[] classz = target.getClass().getInterfaces();
Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
.getMethod().getParameterTypes();
try {
Method m = classz[0].getMethod(method, parameterTypes);
System.out.println(m.getName());
if (m != null && m.isAnnotationPresent(DataSource.class)) {
DataSource data = m.getAnnotation(DataSource.class);
System.out.println("==============================={}"+data.value());
HandleDataSource.putDataSource(data.value());
}else{
System.out.println("000000000000000000000");
} } catch (Exception e) {
e.printStackTrace();
}
}
}
注意: 黄色高亮部分,利用反射读取 Interface的 的定义(包括annotation 的申明);动态读取参数,进行数据源切换;
4. 定义接口服务
package com.robin.it.permission.service; import com.robin.it.ds.DataSource;
import com.robin.it.permission.module.User; /**
* Created by Robin.yi on 2015-4-11.
*/
public interface IUserService { @DataSource("read")
public User getUser(Integer userId); @DataSource("read")
public User getUser(String account, String password); @DataSource("write")
public void insertUser(User user);
}
主意:上面是决定走读库/写库的语句: @DataSource("write") / @DataSource("read")
接口的实现无特别说明,此次省略。
5. 整个Spring 的applicationContent.xml 文件配置如下:
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.1.xsd "> <description>
This file is used to define the authority info.
</description> <!-- 用于扫描 Spring 的各类annotation bean 变量:
@autowired ; @Resource
-->
<context:annotation-config/> <!-- 用于扫描类中组建:
如: @Controller, @Service, @Component
-->
<context:component-scan base-package="com.robin.it.permission.*">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan> <tx:annotation-driven /> <bean id="configProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreResourceNotFound" value="false" />
<property name="locations">
<list>
<!-- 这里支持多种寻址方式:classpath和file -->
<value>classpath:/database.properties</value>
<value>classpath:/config.properties</value>
<!-- 推荐使用file的方式引入,这样可以将配置和代码分离 -->
<!-- <value>file:/opt/demo/config/demo-message.properties</value>-->
</list>
</property>
</bean> <util:properties id="props" location="classpath:/config.properties"/> <!-- MYSQL 配置 --> <bean id="readDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${mysql.jdbc.driverClassName}</value></property>
<property name="url"><value>${mysql.jdbc.url}</value></property>
<property name="username"><value>${mysql.jdbc.username}</value></property>
<property name="password"><value>${mysql.jdbc.password}</value></property>
</bean> <bean id="writeDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName"><value>${mysql2.jdbc.driverClassName}</value></property>
<property name="url"><value>${mysql2.jdbc.url}</value></property>
<property name="username"><value>${mysql2.jdbc.username}</value></property>
<property name="password"><value>${mysql2.jdbc.password}</value></property>
</bean> <bean id="dataSource" class="com.robin.it.ds.ChooseDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<!-- write -->
<entry key="write" value-ref="writeDataSource"/>
<!-- read -->
<entry key="read" value-ref="readDataSource"/>
</map> </property>
<property name="defaultTargetDataSource" ref="writeDataSource"/>
</bean> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean> <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 指定sqlMapConfig总配置文件,订制的environment在spring容器中不在生效-->
<property name="configLocation" value="classpath:mybatis-config-mysql.xml"/>
<!--指定实体类映射文件,可以指定同时指定某一包以及子包下面的所有配置文件,mapperLocations和configLocation有一个即可,
当需要为实体类指定别名时,可指定configLocation属性,再在mybatis总配置文件中采用mapper引入实体类映射文件 -->
<property name="mapperLocations">
<list>
<value>classpath*:/mysqlmapper/*Mapper.xml</value>
</list>
</property>
</bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.robin.it.permission.dao" />
<!-- optional unless there are multiple session factories defined -->
<property name="sqlSessionFactoryBeanName" value="sessionFactory" />
</bean> <aop:aspectj-autoproxy proxy-target-class="true"/> <bean id="dataSourceAspect" class="com.robin.it.ds.DataSourceAspect" /> <aop:config>
<aop:aspect id="c" ref="dataSourceAspect">
<aop:pointcut id="tx" expression="execution(* com.robin.it.permission.service.*.*(..))"/>
<aop:before pointcut-ref="tx" method="before"/>
</aop:aspect>
</aop:config>
</beans>
重点关注标为黄色的部分: 如何配置多数据源; 当知悉对应service [com.robin.it.permission.service.*.*(..)] , 的相关方法之前(aop:before), 执行DataSourceAspect切面方法;
数据库配置文件database.properties 参考,上一章节。
到此,已完成多数据源的,读写分离配置。
Spring 数据源配置三:多数据源的更多相关文章
- spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式
spring+hibernate 配置多个数据源过程 以及 spring中数据源的配置方式[部分内容转载] 2018年03月27日 18:58:41 守望dfdfdf 阅读数:62更多 个人分类: 工 ...
- spring+mybatis配置多个数据源
http://www.cnblogs.com/lzrabbit/p/3750803.html
- 【spring boot】12.spring boot对多种不同类型数据库,多数据源配置使用
2天时间,终于把spring boot下配置连接多种不同类型数据库,配置多数据源实现! ======================================================== ...
- spring基于通用Dao的多数据源配置详解【ds1】
spring基于通用Dao的多数据源配置详解 有时候在一个项目中会连接多个数据库,需要在spring中配置多个数据源,最近就遇到了这个问题,由于我的项目之前是基于通用Dao的,配置的时候问题不断,这种 ...
- spring基于通用Dao的多数据源配置
有时候在一个项目中会连接多个数据库,须要在spring中配置多个数据源,近期就遇到了这个问题,因为我的项目之前是基于通用Dao的,配置的时候问题不断.这样的方式和资源文件冲突:扫描映射文件的话,Sql ...
- Springboot 多数据源配置,结合tk-mybatis
一.前言 作为一个资深的CRUD工程师,我们在实际使用springboot开发项目的时候,难免会遇到同时使用多个数据库的情况,比如前脚刚查询mysql,后脚就要查询sqlserver. 这时,我们很直 ...
- 在Spring中配置SQL server 2000
前言 Lz主要目的是在Spring中配置SQL server 2000数据库,但实现目的的过程中参差着许多SQL server 2000的知识,也包罗在本文记载下来!(Lz为什么要去搞sql serv ...
- 搞定SpringBoot多数据源(2):动态数据源
目录 1. 引言 2. 动态数据源流程说明 3. 实现动态数据源 3.1 说明及数据源配置 3.1.1 包结构说明 3.1.2 数据库连接信息配置 3.1.3 数据源配置 3.2 动态数据源设置 3. ...
- Spring:(三) --常见数据源及声明式事务配置
Spring自带了一组数据访问框架,集成了多种数据访问技术.无论我们是直接通过 JDBC 还是像Hibernate或Mybatis那样的框架实现数据持久化,Spring都可以为我们消除持久化代码中那些 ...
随机推荐
- tomcat中的webapps
使用IDE方便开发,使用文本编辑器建立Web工程,有助于理解工程的各个文件组成及底层原理.需搭建好服务器(常用tomcat),当然需要Java运行环境了. 一.建立JSP文件,如helloworld. ...
- SQLite本地事务处理
private void toolStripButton1_Click(object sender, EventArgs e) { //判断新增的年度是否已经存在 if (HasYear()) { M ...
- linq to sql 三层架构中使用CRUD操作
/// <summary> /// 数据层 /// </summary> public partial class GasBottles : IGasBottles { #re ...
- DevExpress - cxGrid 使用方法
如何设置多选,并对多个选中行进行数据处理. 1.首先需要将需要获取的字段的列添加到 Grid 中,例如 grdDemoColumn1. 2.将 Grid 的 OptionsSelection 中的 C ...
- DuiLib(二)——控件创建
上一篇讲了窗口及消息,了解了大体的程序框架.这一篇说的是控件的创建. duilib支持XML配置文件,即根据XML创建窗口及控件,将界面与逻辑分开,便于修改及维护.上一篇的示例中可以看到在消息WM_C ...
- python的一些总结5
上面4都是水的 恩每篇都一点知识点 用来写给不耐烦的人看..哈哈这篇 争取不水. 上面4篇如果 掌握 基本上是 80%常用的代码了. 1.下面讲一下 比较常用的代码: macro(jinja 上的功能 ...
- synthesize(合成) keyword in IOS
synthesize creates setter and getter (从Objective-C 2.0开始,合成可自动生成存取方法) the setter is used by IOS to s ...
- Android开发 将数据保存到SD卡
前言: 使用Activity的openFileOutput()方法保存文件,文件是存放在手机空间上,一般手机的存储空间不是很大,存放些小文件还行,如果要存放像视频这样的大文件,是不可行的.对于像视频这 ...
- C#多线程学习(一) 多线程的相关概念
什么是进程?当一个程序开始运行时,它就是一个进程,进程包括运行中的程序和程序所使用到的内存和系统资源.而一个进程又是由多个线程所组成的. 什么是线程?线程是程序中的一个执行流,每个线程都有自己的专有寄 ...
- 【双十一到了,准备买书了么?】推荐几本c/c++入手的书籍
<C和指针>c语言的经典之作,全书共18章,覆盖了数据.语句.操作符和表达式.指针.函数.数组.字符串.结构和联合等几乎所有重要的C编程话题.而且每章后面都有基础回顾已经较多例程,很适合入 ...