介绍下mysql数据库读写分离在spring,hibernate框架下的配置。
1.mysql连接配置文件jdbc.properties
master.*.*表示主数据库连接参数,负责增,删,改;
slave.*.*表示从数据库连接参数,只负责读取;
jdbc.properties
2.配置AOP切面类 DataSourceAdvice.java
数据源选择类 DataSourceSwitcher.java
DynamicDataSource.java数据源动态切换类
下面配置spring applicationContext.xml文件
!注 applicationContenxt.xml中
<!-- 切换数据源 -->
<bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor
pointcut="execution(* cn.com.company.service..*Service.*(..))"
advice-ref="dataSourceAdvice" />
</aop:config>
一定要配置在事务AOP之上
1.mysql连接配置文件jdbc.properties
master.*.*表示主数据库连接参数,负责增,删,改;
slave.*.*表示从数据库连接参数,只负责读取;
jdbc.properties
- master.jdbc.driverClassName=com.mysql.jdbc.Driver
- master.jdbc.url=********
- master.jdbc.username=********
- master.jdbc.password=********
- slave.jdbc.driverClassName=com.mysql.jdbc.Driver
- slave.jdbc.url=********
- slave.jdbc.username=********
- slave.jdbc.password=********
master.jdbc.driverClassName=com.mysql.jdbc.Driver master.jdbc.url=******** master.jdbc.username=******** master.jdbc.password=******** slave.jdbc.driverClassName=com.mysql.jdbc.Driver slave.jdbc.url=******** slave.jdbc.username=******** slave.jdbc.password=********把**改成你所需的连接参数;
2.配置AOP切面类 DataSourceAdvice.java
- import java.lang.reflect.Method;
- import org.springframework.aop.AfterReturningAdvice;
- import org.springframework.aop.MethodBeforeAdvice;
- import org.springframework.aop.ThrowsAdvice;
- import com.company.datasource.DataSourceSwitcher;
- public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {
- // service方法执行之前被调用
- public void before(Method method, Object[] args, Object target) throws Throwable {
- System.out.println("切入点: " + target.getClass().getName() + "类中" + method.getName() + "方法");
- if(method.getName().startsWith("add")
- || method.getName().startsWith("create")
- || method.getName().startsWith("save")
- || method.getName().startsWith("edit")
- || method.getName().startsWith("update")
- || method.getName().startsWith("delete")
- || method.getName().startsWith("remove")){
- System.out.println("切换到: master");
- DataSourceSwitcher.setMaster();
- }
- else {
- System.out.println("切换到: slave");
- DataSourceSwitcher.setSlave();
- }
- }
- // service方法执行完之后被调用
- public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
- }
- // 抛出Exception之后被调用
- public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable {
- DataSourceSwitcher.setSlave();
- System.out.println("出现异常,切换到: slave");
- }
- }
import java.lang.reflect.Method; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.ThrowsAdvice; import com.company.datasource.DataSourceSwitcher; public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice { // service方法执行之前被调用 public void before(Method method, Object[] args, Object target) throws Throwable { System.out.println("切入点: " + target.getClass().getName() + "类中" + method.getName() + "方法"); if(method.getName().startsWith("add") || method.getName().startsWith("create") || method.getName().startsWith("save") || method.getName().startsWith("edit") || method.getName().startsWith("update") || method.getName().startsWith("delete") || method.getName().startsWith("remove")){ System.out.println("切换到: master"); DataSourceSwitcher.setMaster(); } else { System.out.println("切换到: slave"); DataSourceSwitcher.setSlave(); } } // service方法执行完之后被调用 public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable { } // 抛出Exception之后被调用 public void afterThrowing(Method method, Object[] args, Object target, Exception ex) throws Throwable { DataSourceSwitcher.setSlave(); System.out.println("出现异常,切换到: slave"); } }
数据源选择类 DataSourceSwitcher.java
- package com.company.datasource;
- import org.springframework.util.Assert;
- public class DataSourceSwitcher {
- @SuppressWarnings("rawtypes")
- private static final ThreadLocal contextHolder = new ThreadLocal();
- @SuppressWarnings("unchecked")
- public static void setDataSource(String dataSource) {
- Assert.notNull(dataSource, "dataSource cannot be null");
- contextHolder.set(dataSource);
- }
- public static void setMaster(){
- clearDataSource();
- }
- public static void setSlave() {
- setDataSource("slave");
- }
- public static String getDataSource() {
- return (String) contextHolder.get();
- }
- public static void clearDataSource() {
- contextHolder.remove();
- }
- }
package com.company.datasource; import org.springframework.util.Assert; public class DataSourceSwitcher { @SuppressWarnings("rawtypes") private static final ThreadLocal contextHolder = new ThreadLocal(); @SuppressWarnings("unchecked") public static void setDataSource(String dataSource) { Assert.notNull(dataSource, "dataSource cannot be null"); contextHolder.set(dataSource); } public static void setMaster(){ clearDataSource(); } public static void setSlave() { setDataSource("slave"); } public static String getDataSource() { return (String) contextHolder.get(); } public static void clearDataSource() { contextHolder.remove(); } }
DynamicDataSource.java数据源动态切换类
- package com.company.datasource;
- import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
- public class DynamicDataSource extends AbstractRoutingDataSource {
- @Override
- protected Object determineCurrentLookupKey() {
- return DataSourceSwitcher.getDataSource();
- }
- }
package com.company.datasource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceSwitcher.getDataSource(); } }
下面配置spring applicationContext.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:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
- xsi:schemaLocation="
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context-3.0.xsd">
- <context:annotation-config />
- <!-- 自动加载SERVICE DAO ACTION -->
- <context:component-scan base-package="cn.com.company.dao.*" />
- <context:component-scan base-package="cn.com.company.service.*" />
- <context:component-scan base-package="cn.com.company.action" />
- <!-- 加载properties配置文件 -->
- <bean id="propertyConfigurer"
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:jdbc.properties</value>
- </list>
- </property>
- </bean>
- <bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
- //***c3p0配置
- </bean>
- <!-- 主数据源-->
- <bean id="masterDataSource" parent="parentDataSource">
- <property name="driverClass" value="${master.jdbc.driverClassName}" />
- <property name="jdbcUrl" value="${master.jdbc.url}" />
- <property name="user" value="${master.jdbc.username}" />
- <property name="password" value="${master.jdbc.password}" />
- </bean>
- <!-- 从数据源-->
- <bean id="slaveDataSource" parent="parentDataSource">
- <property name="driverClass" value="${slave.jdbc.driverClassName}" />
- <property name="jdbcUrl" value="${slave.jdbc.url}" />
- <property name="user" value="${slave.jdbc.username}" />
- <property name="password" value="${slave.jdbc.password}" />
- </bean>
- <bean id="dataSource" class="com.company.datasource.DynamicDataSource">
- <property name="targetDataSources">
- <map key-type="java.lang.String">
- <entry key="slave" value-ref="slaveDataSource" />
- </map>
- </property>
- <property name="defaultTargetDataSource" ref="masterDataSource" />
- </bean>
- <!-- 配置sessionFactory -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
- <property name="dataSource" ref="dataSource"></property>
- <property name="packagesToScan" value="cn.com.company.entity" />
- <property name="hibernateProperties">
- <props>
- <prop>//***hibernate一些参数这里不写了</prop>
- </props>
- </property>
- </bean>
- <!-- 切换数据源 -->
- <bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />
- <aop:config>
- <aop:advisor
- pointcut="execution(* cn.com.company.service..*Service.*(..))"
- advice-ref="dataSourceAdvice" />
- </aop:config>
- <!-- 配置事务管理器 -->
- <bean id="transactionManager"
- class="org.springframework.orm.hibernate3.HibernateTransactionManager">
- <property name="sessionFactory">
- <ref bean="sessionFactory" />
- </property>
- </bean>
- <!--配置事务的传播特性 -->
- <tx:advice id="txAdvice" transaction-manager="transactionManager">
- <tx:attributes>
- <!-- 对增、删、改方法进行事务支持 -->
- <tx:method name="add*" propagation="REQUIRED" />
- <tx:method name="create*" propagation="REQUIRED" />
- <tx:method name="save*" propagation="REQUIRED" />
- <tx:method name="edit*" propagation="REQUIRED" />
- <tx:method name="update*" propagation="REQUIRED" />
- <tx:method name="delete*" propagation="REQUIRED" />
- <tx:method name="remove*" propagation="REQUIRED" />
- <!-- 对查找方法进行只读事务 -->
- <tx:method name="loadByUsername*" propagation="SUPPORTS" read-only="true" />
- <!-- 对其它方法进行只读事务 -->
- <tx:method name="*" propagation="SUPPORTS" read-only="true" />
- </tx:attributes>
- </tx:advice>
- <!--那些类的哪些方法参与事务 -->
- <aop:config>
- <aop:advisor
- pointcut="execution(* cn.com.company.service..*Service.*(..))"
- advice-ref="txAdvice" />
- <aop:advisor
- pointcut="execution(* cn.com.company.service..*ServiceImpl.*(..))"
- advice-ref="txAdvice" />
- </aop:config>
- </beans>
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:annotation-config /> <!-- 自动加载SERVICE DAO ACTION --> <context:component-scan base-package="cn.com.company.dao.*" /> <context:component-scan base-package="cn.com.company.service.*" /> <context:component-scan base-package="cn.com.company.action" /> <!-- 加载properties配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> </list> </property> </bean> <bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> //***c3p0配置 </bean> <!-- 主数据源--> <bean id="masterDataSource" parent="parentDataSource"> <property name="driverClass" value="${master.jdbc.driverClassName}" /> <property name="jdbcUrl" value="${master.jdbc.url}" /> <property name="user" value="${master.jdbc.username}" /> <property name="password" value="${master.jdbc.password}" /> </bean> <!-- 从数据源--> <bean id="slaveDataSource" parent="parentDataSource"> <property name="driverClass" value="${slave.jdbc.driverClassName}" /> <property name="jdbcUrl" value="${slave.jdbc.url}" /> <property name="user" value="${slave.jdbc.username}" /> <property name="password" value="${slave.jdbc.password}" /> </bean> <bean id="dataSource" class="com.company.datasource.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="slave" value-ref="slaveDataSource" /> </map> </property> <property name="defaultTargetDataSource" ref="masterDataSource" /> </bean> <!-- 配置sessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="packagesToScan" value="cn.com.company.entity" /> <property name="hibernateProperties"> <props> <prop>//***hibernate一些参数这里不写了</prop> </props> </property> </bean> <!-- 切换数据源 --> <bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" /> <aop:config> <aop:advisor pointcut="execution(* cn.com.company.service..*Service.*(..))" advice-ref="dataSourceAdvice" /> </aop:config> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory"> <ref bean="sessionFactory" /> </property> </bean> <!--配置事务的传播特性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 对增、删、改方法进行事务支持 --> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="create*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <!-- 对查找方法进行只读事务 --> <tx:method name="loadByUsername*" propagation="SUPPORTS" read-only="true" /> <!-- 对其它方法进行只读事务 --> <tx:method name="*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!--那些类的哪些方法参与事务 --> <aop:config> <aop:advisor pointcut="execution(* cn.com.company.service..*Service.*(..))" advice-ref="txAdvice" /> <aop:advisor pointcut="execution(* cn.com.company.service..*ServiceImpl.*(..))" advice-ref="txAdvice" /> </aop:config> </beans>
!注 applicationContenxt.xml中
<!-- 切换数据源 -->
<bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />
<aop:config>
<aop:advisor
pointcut="execution(* cn.com.company.service..*Service.*(..))"
advice-ref="dataSourceAdvice" />
</aop:config>
一定要配置在事务AOP之上
相关推荐
本文详细介绍了如何在Spring Boot项目中实现主从数据库配置及读写分离功能。通过以上步骤,我们可以有效地提升应用程序的性能和可靠性。需要注意的是,在实际部署过程中还需考虑更多因素,如网络延迟、数据同步的...
ShardingJDBC作为一款轻量级的Java框架,能够有效地解决大数据量下的分库分表、读写分离等问题,提高系统的并发处理能力。本文将通过一个基于SpringBoot、Mybatis-Plus和Druid的数据源管理的完整示例,详细介绍如何...
本示例将详细解释如何利用Sharding-jdbc在MySQL数据库上实现读写分离,以及如何配置和运行提供的代码。 首先,我们需要理解读写分离的基本概念。在高并发的场景下,为了提高数据库系统的性能,通常会将读操作和写...
zookeeper作为注册中心web服务部署较多,nginx反向代理,其中要实现session共享,采用spring-session的redis集群存储方案mysql主从复制,读写分离3技术要点摘要spring-boot、spring-session、spring-security等全家...
config-server 配置服务端2设计方案采用dubbo实现分布式rpc,zookeeper作为注册中心web服务部署多个,nginx反向代理,其中要实现session共享,采用spring-session的redis集群存储方案mysql主从复制,读写分离3技术...
mysql主从复制,读写分离 3技术要点 后端: spring-boot、spring-session、spring-security等全家桶 dubbo + zookeeper分布式rpc服务 redis缓存 mysql数据库 flowable工作流 mybatis、jdbcTemplate、spring jpa持久...
mysql主从复制,读写分离 3技术要点 后端: spring-boot、spring-session、spring-security等全家桶 dubbo + zookeeper分布式rpc服务 redis缓存 mysql数据库 flowable工作流 mybatis、jdbcTemplate、spring jpa持久...
│ Java面试题72:数据库的读写分离.mp4 │ Java面试题73:数据库优化之缓存.mp4 │ Java面试题74:sql语句优化小技巧.mp4 │ Java面试题75:批量插入几百万条数据.mp4 │ Java面试题76:有没有使用过redis.mp4 │ ...
- **读写分离**:通过MySQL主从复制和MyCat实现读写分离,减轻主数据库的压力。 #### 三、架构优化思路 1. **Spring Cloud vs Dubbo**: - **区别**:虽然两者都可以作为微服务架构的解决方案,但Spring Cloud ...
13. **分布式数据库**: 当数据量大或者需要高可用性时,可能需要用到分布式数据库,如分片、读写分离、主从复制等策略,理解这些概念对大型项目开发至关重要。 这个"Java数据库系统项目开发实践"会覆盖以上所有知识...
* 熟练应用 MySQL(了解分布式集群主从备份、读写分离)、Orcale 等关系型数据库。 * 熟悉 Redis 数据库。 * 熟悉 Lucene、Solr 了解搜索引擎的运行原理。 * 熟练使用 SVN、Maven 等项目开发及管理工具。 * 熟悉 ...
- MySQL主从复制,读写分离 - Spring Async - Spring Cache - Swagger - Spring Test - MockMvc - HTTPS - Spring DevTools - Spring Actuator - Logback+Slf4j多环境日志 - i18n - Maven Multi-Module - WebSocket ...
3. **数据库读写分离**:主从复制实现读写分离,减轻主数据库压力。 八、论文部分 论文通常会详细阐述系统的设计思路、架构选择、关键技术实现以及遇到的问题和解决方案,是理解和复现项目的重要参考资料。 总的来...
标题中的“Multiple_DB_With_Cluster_MySql_MongoDB”表明这是一个关于使用集群环境下的MySQL和MongoDB的项目。这个项目可能涉及了如何在分布式系统中管理和操作多个数据库,包括关系型数据库MySQL和非关系型数据库...
2. 数据库集群和负载均衡:通过主从复制、分布式数据库等方式提高可用性和读写性能。 3. 存储过程:存储过程是预编译的SQL集合,可以提高执行效率,封装业务逻辑,减少网络通信。 4. 触发器:在满足特定条件时自动...
4. **数据库管理**:他对MySQL数据库有深入实践,能够编写和优化SQL语句,同时了解MySQL的主从复制和读写分离策略,这有助于提高数据库系统的可用性和扩展性。 5. **中间件与搜索引擎**:高亚林使用过Lucene/Solr...
可以使用如MySQL的主从复制或分布式数据库解决方案。 6. **Tomcat并发**:Tomcat的并发能力取决于多个因素,包括硬件资源、配置参数(如最大线程数)。实际能支持的并发用户数量需要结合具体环境测试评估。 7. **...
- 熟练使用MySQL数据库,具备SQL语句优化能力,并了解MySQL的主从复制和读写分离,这有助于提升数据库性能和高可用性。 - 熟悉Lucene/Solr全文检索技术,能够实现高效的搜索功能,还掌握了ActiveMQ消息中间件,可...
BeetSql原生支持主从数据库架构,可以在多服务器环境中实现读写分离。 #### 十八、SHARDING-JDBC支持 BeetSql与Sharding-JDBC等分布式数据库中间件兼容良好,支持水平分片等特性。 #### 十九、跨数据库平台 ...