注解方式实现读写分离
2017-01-16 10:07
99 查看
注解方式实现读写分离
在web应用开发过程中,数据库的压力会越来越大,那么就避免不了,要提供一个比较可行的方案,数据库的读写分离。读写分离的机制:在从库读取数据,在主库写数据。
1.自定义数据库数据源类型注解:
@Target( ElementType.METHOD) @Retention( RetentionPolicy.RUNTIME) @Inherited public @interface DBProfile { String dbName() default ""; }
2.在方法层面上调用:
@DBProfile(dbName = Constants.SLAVE)
3.用ThreadLocal,定义数据源的类型(主,从)
public class DataSourceContextHolder { private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); /** * @Description: 设置数据源类型 * @param dataSourceType 数据库类型 * @return void * @throws */ public static void setDataSourceType(String dataSourceType) { contextHolder.set(dataSourceType); } /** * @Description: 获取数据源类型 * @param * @return String * @throws */ public static String getDataSourceType() { return contextHolder.get(); } /** * @Description: 清除数据源类型 * @param * @return void * @throws */ public static void clearDataSourceType() { contextHolder.remove(); } }
4.定义动态数据源类
public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { return DataSourceContextHolder.getDataSourceType(); } }
5.在xml中配置,
DynamicDataSource
<bean id="dynamicDataSource" class="com.xx.xx.business.service.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry value-ref="dataSource" key="Master"/> <entry value-ref="dataSource" key="Slave"/> <!-- <entry value-ref="businessDataSourceOther" key="Slave"/> --> </map> </property> <!--默认数据源--> <property name="defaultTargetDataSource" ref="dataSource"/> </bean> <bean id="dataSourceMaster" class="dbcp.xxx">
<bean id="dataSourceSlaver" class="dbcp.xxx">
6.定义切面
@Component @Aspect public class DynamicDataSourceAspect { @Pointcut( "@annotation(com.xx.xx.xx.common.aspect.DBProfile)" ) public void DynamicDataSource() { } @Before( "DynamicDataSource()" ) public void executeChangeDataSource( JoinPoint point ) { MethodSignature msig = ( MethodSignature )point.getSignature(); Method method = msig.getMethod(); DBProfile dbProfile = ( DBProfile )method.getAnnotation( DBProfile.class ); if( dbProfile != null ) { DataSourceContextHolder.setDataSourceType( dbProfile.dbName() ); } } @After( "DynamicDataSource()" ) public void executeClear( JoinPoint point ) { DataSourceContextHolder.clearDataSourceType(); } }
相关文章推荐
- 用Spring配置文件或者注解方式实现AOP
- hibernate注解方式实现复合主键
- 使用Spring的注解方式实现AOP
- AOP实现_AOP中的概念_注解方式_XML配置方式声明切面
- spring mvc注解方式实现向导式跳转页面
- ITCAST视频-Spring学习笔记(使用Spring的注解方式实现AOP入门)
- (9) 使用Spring的注解方式实现AOP入门 以及 细节
- Spring学习笔记(14)----使用Spring的注解方式实现AOP
- Spring整理11 -- 面对切面(AOP)1 -- 注解配置的方式实现AOP
- struts2注解方式实现数据验证
- 用Spring配置文件或者注解方式实现AOP
- 第五章 Spring进阶-注解方式实现AOP(3)-全文完
- 第五章 Spring进阶-注解方式实现AOP(2)
- 注解方式实现 Hibernate 的双向一对多关系的映射
- Spring的AOP分为注解和配置两种方式实现
- hibernate注解方式实现复合主键
- 第五章 Spring进阶-注解方式实现AOP(1)
- 使用Spring的注解方式实现AOP的细节
- spring 注解方式实现依赖注入
- (10) 使用Spring的注解方式实现AOP入门 以及 细节