如何在Spring中使用MyBatis實現(xiàn)數(shù)據(jù)的讀寫分離?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
成都創(chuàng)新互聯(lián)公司主要從事網(wǎng)頁設(shè)計、PC網(wǎng)站建設(shè)(電腦版網(wǎng)站建設(shè))、wap網(wǎng)站建設(shè)(手機版網(wǎng)站建設(shè))、成都響應(yīng)式網(wǎng)站建設(shè)、程序開發(fā)、網(wǎng)站優(yōu)化、微網(wǎng)站、微信小程序開發(fā)等,憑借多年來在互聯(lián)網(wǎng)的打拼,我們在互聯(lián)網(wǎng)網(wǎng)站建設(shè)行業(yè)積累了豐富的成都網(wǎng)站設(shè)計、網(wǎng)站制作、網(wǎng)站設(shè)計、網(wǎng)絡(luò)營銷經(jīng)驗,集策劃、開發(fā)、設(shè)計、營銷、管理等多方位專業(yè)化運作于一體。
其實現(xiàn)原理如下:
通過Spring AOP對dao層接口進行攔截,并對需要指定數(shù)據(jù)源的接口在ThradLocal中設(shè)置其數(shù)據(jù)源類型及名稱
通過MyBatsi的插件,對根據(jù)更新或者查詢操作在ThreadLocal中設(shè)置數(shù)據(jù)源(dao層沒有指定的情況下)
繼承AbstractRoutingDataSource類。
在此直接寫死使用HikariCP作為數(shù)據(jù)源
其實現(xiàn)步驟如下:
定義其數(shù)據(jù)源配置文件并進行解析為數(shù)據(jù)源
定義AbstractRoutingDataSource類及其它注解
定義Aop攔截
定義MyBatis插件
整合在一起
1.配置及解析類
其配置參數(shù)直接使用HikariCP的配置,其具體參數(shù)可以參考HikariCP。
在此使用yaml
格式,名稱為datasource.yaml
,內(nèi)容如下:
dds: write: jdbcUrl: jdbc:MySQL://localhost:3306/order password: liu123 username: root maxPoolSize: 10 minIdle: 3 poolName: master read: - jdbcUrl: jdbc:mysql://localhost:3306/test password: liu123 username: root maxPoolSize: 10 minIdle: 3 poolName: slave1 - jdbcUrl: jdbc:mysql://localhost:3306/test2 password: liu123 username: root maxPoolSize: 10 minIdle: 3 poolName: slave2
定義該配置所對應(yīng)的Bean,名稱為DBConfig,內(nèi)容如下:
@Component @ConfigurationProperties(locations = "classpath:datasource.yaml", prefix = "dds") public class DBConfig { private Listread; private HikariConfig write; public List getRead() { return read; } public void setRead(List read) { this.read = read; } public HikariConfig getWrite() { return write; } public void setWrite(HikariConfig write) { this.write = write; } }
把配置轉(zhuǎn)換為DataSource的工具類,名稱:DataSourceUtil
,內(nèi)容如下:
import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import javax.sql.DataSource; import java.util.ArrayList; import java.util.List; public class DataSourceUtil { public static DataSource getDataSource(HikariConfig config) { return new HikariDataSource(config); } public static ListgetDataSource(List configs) { List result = null; if (configs != null && configs.size() > 0) { result = new ArrayList<>(configs.size()); for (HikariConfig config : configs) { result.add(getDataSource(config)); } } else { result = new ArrayList<>(0); } return result; } }
2.注解及動態(tài)數(shù)據(jù)源
定義注解@DataSource,其用于需要對個別方法指定其要使用的數(shù)據(jù)源(如某個讀操作需要在master上執(zhí)行,但另一讀方法b需要在讀數(shù)據(jù)源的具體一臺上面執(zhí)行)
@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DataSource { /** * 類型,代表是使用讀還是寫 * @return */ DataSourceType type() default DataSourceType.WRITE; /** * 指定要使用的DataSource的名稱 * @return */ String name() default ""; }
定義數(shù)據(jù)源類型,分為兩種:READ,WRITE,內(nèi)容如下:
public enum DataSourceType { READ, WRITE; }
定義保存這此共享信息的類DynamicDataSourceHolder
,在其中定義了兩個ThreadLocal
和一個map,holder
用于保存當(dāng)前線程的數(shù)據(jù)源類型(讀或者寫),pool
用于保存數(shù)據(jù)源名稱(如果指定),其內(nèi)容如下:
import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class DynamicDataSourceHolder { private static final Mapcache = new ConcurrentHashMap<>(); private static final ThreadLocal holder = new ThreadLocal<>(); private static final ThreadLocal pool = new ThreadLocal<>(); public static void putToCache(String key, DataSourceType dataSourceType) { cache.put(key,dataSourceType); } public static DataSourceType getFromCach(String key) { return cache.get(key); } public static void putDataSource(DataSourceType dataSourceType) { holder.set(dataSourceType); } public static DataSourceType getDataSource() { return holder.get(); } public static void putPoolName(String name) { if (name != null && name.length() > 0) { pool.set(name); } } public static String getPoolName() { return pool.get(); } public static void clearDataSource() { holder.remove(); pool.remove(); } }
動態(tài)數(shù)據(jù)源類為DynamicDataSoruce
,其繼承自AbstractRoutingDataSource
,可以根據(jù)返回的key切換到相應(yīng)的數(shù)據(jù)源,其內(nèi)容如下:
import com.zaxxer.hikari.HikariDataSource; import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource; import javax.sql.DataSource; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ThreadLocalRandom; public class DynamicDataSource extends AbstractRoutingDataSource { private DataSource writeDataSource; private ListreadDataSource; private int readDataSourceSize; private Map dataSourceMapping = new ConcurrentHashMap<>(); @Override public void afterPropertiesSet() { if (this.writeDataSource == null) { throw new IllegalArgumentException("Property 'writeDataSource' is required"); } setDefaultTargetDataSource(writeDataSource); Map
3.AOP攔截
如果在相應(yīng)的dao層做了自定義配置(指定數(shù)據(jù)源),則在些處理。解析相應(yīng)方法上的@DataSource
注解,如果存在,并把相應(yīng)的信息保存至上面的DynamicDataSourceHolder
中。在此對com.hfjy.service.order.dao
包進行做攔截。內(nèi)容如下:
import com.hfjy.service.order.anno.DataSource; import com.hfjy.service.order.wr.DynamicDataSourceHolder; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import java.lang.reflect.Method; /** * 使用AOP攔截,對需要特殊方法可以指定要使用的數(shù)據(jù)源名稱(對應(yīng)為連接池名稱) */ @Aspect @Component public class DynamicDataSourceAspect { @Pointcut("execution(public * com.hfjy.service.order.dao.*.*(*))") public void dynamic(){} @Before(value = "dynamic()") public void beforeOpt(JoinPoint point) { Object target = point.getTarget(); String methodName = point.getSignature().getName(); Class>[] clazz = target.getClass().getInterfaces(); Class>[] parameterType = ((MethodSignature)point.getSignature()).getMethod().getParameterTypes(); try { Method method = clazz[0].getMethod(methodName,parameterType); if (method != null && method.isAnnotationPresent(DataSource.class)) { DataSource datasource = method.getAnnotation(DataSource.class); DynamicDataSourceHolder.putDataSource(datasource.type()); String poolName = datasource.name(); DynamicDataSourceHolder.putPoolName(poolName); DynamicDataSourceHolder.putToCache(clazz[0].getName() + "." + methodName, datasource.type()); } } catch (Exception e) { e.printStackTrace(); } } @After(value = "dynamic()") public void afterOpt(JoinPoint point) { DynamicDataSourceHolder.clearDataSource(); } }
4.MyBatis插件
如果在dao層沒有指定相應(yīng)的要使用的數(shù)據(jù)源,則在此進行攔截,根據(jù)是更新還是查詢設(shè)置數(shù)據(jù)源的類型,內(nèi)容如下:
import org.apache.ibatis.executor.Executor; import org.apache.ibatis.mapping.MappedStatement; import org.apache.ibatis.mapping.SqlCommandType; import org.apache.ibatis.plugin.*; import org.apache.ibatis.session.ResultHandler; import org.apache.ibatis.session.RowBounds; import java.util.Properties; @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}), @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}) }) public class DynamicDataSourcePlugin implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { MappedStatement ms = (MappedStatement)invocation.getArgs()[0]; DataSourceType dataSourceType = null; if ((dataSourceType = DynamicDataSourceHolder.getFromCach(ms.getId())) == null) { if (ms.getSqlCommandType().equals(SqlCommandType.SELECT)) { dataSourceType = DataSourceType.READ; } else { dataSourceType = DataSourceType.WRITE; } DynamicDataSourceHolder.putToCache(ms.getId(), dataSourceType); } DynamicDataSourceHolder.putDataSource(dataSourceType); return invocation.proceed(); } @Override public Object plugin(Object target) { if (target instanceof Executor) { return Plugin.wrap(target, this); } else { return target; } } @Override public void setProperties(Properties properties) { } }
5.整合
在里面定義MyBatis要使用的內(nèi)容及DataSource
,內(nèi)容如下:
import com.hfjy.service.order.wr.DBConfig; import com.hfjy.service.order.wr.DataSourceUtil; import com.hfjy.service.order.wr.DynamicDataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.annotation.Resource; import javax.sql.DataSource; @Configuration @MapperScan(value = "com.hfjy.service.order.dao", sqlSessionFactoryRef = "sqlSessionFactory") public class DataSourceConfig { @Resource private DBConfig dbConfig; @Bean(name = "dataSource") public DynamicDataSource dataSource() { DynamicDataSource dataSource = new DynamicDataSource(); dataSource.setWriteDataSource(DataSourceUtil.getDataSource(dbConfig.getWrite())); dataSource.setReadDataSource(DataSourceUtil.getDataSource(dbConfig.getRead())); return dataSource; } @Bean(name = "transactionManager") public DataSourceTransactionManager dataSourceTransactionManager(@Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean(); sessionFactoryBean.setConfigLocation(new ClassPathResource("mybatis-config.xml")); sessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources("classpath*:mapper/*.xml")); sessionFactoryBean.setDataSource(dataSource); return sessionFactoryBean.getObject(); } }
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。