<pre id="bbfd9"><del id="bbfd9"><dfn id="bbfd9"></dfn></del></pre>

          <ruby id="bbfd9"></ruby><p id="bbfd9"><mark id="bbfd9"></mark></p>

          <p id="bbfd9"></p>

          <p id="bbfd9"><cite id="bbfd9"></cite></p>

            <th id="bbfd9"><form id="bbfd9"><dl id="bbfd9"></dl></form></th>

            <p id="bbfd9"><cite id="bbfd9"></cite></p><p id="bbfd9"></p>
            <p id="bbfd9"><cite id="bbfd9"><progress id="bbfd9"></progress></cite></p>
            java語言

            Spring+MyBatis數據讀寫分離的實例詳解

            時間:2025-02-01 23:52:24 java語言 我要投稿
            • 相關推薦

            Spring+MyBatis數據讀寫分離的實例詳解

              本文介紹了Spring Boot + MyBatis讀寫分離,有需要了解Spring+MyBatis讀寫分離的朋友可參考。想了解更多相關信息請持續關注我們應屆畢業生考試網!

              其最終實現功能:

              1.默認更新操作都使用寫數據源

              2.讀操作都使用slave數據源

              3.特殊設置:可以指定要使用的數據源類型及名稱(如果有名稱,則會根據名稱使用相應的數據源)

              其實現原理如下:

              1.通過Spring AOP對dao層接口進行攔截,并對需要指定數據源的接口在ThradLocal中設置其數據源類型及名稱

              2.通過MyBatsi的插件,對根據更新或者查詢操作在ThreadLocal中設置數據源(dao層沒有指定的情況下)

              3.繼承AbstractRoutingDataSource類。

              在此直接寫死使用HikariCP作為數據源

              其實現步驟如下:

              1.定義其數據源配置文件并進行解析為數據源

              2.定義AbstractRoutingDataSource類及其它注解

              3.定義Aop攔截

              4.定義MyBatis插件

              5.整合在一起

              1.配置及解析類

              其配置參數直接使用HikariCP的配置,其具體參數可以參考HikariCP。

              在此使用yaml格式,名稱為datasource.yaml,內容如下:

              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

              定義該配置所對應的Bean,名稱為DBConfig,內容如下:

              @Component

              @ConfigurationProperties(locations = "classpath:datasource.yaml", prefix = "dds")

              public class DBConfig {

              private List<HikariConfig> read;

              private HikariConfig write;

              public List<HikariConfig> getRead() {

              return read;

              }

              public void setRead(List<HikariConfig> read) {

              this.read = read;

              }

              public HikariConfig getWrite() {

              return write;

              }

              public void setWrite(HikariConfig write) {

              this.write = write;

              }

              }

              把配置轉換為DataSource的工具類,名稱:DataSourceUtil,內容如下:

              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 List<DataSource> getDataSource(List<HikariConfig> configs) {

              List<DataSource> 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.注解及動態數據源

              定義注解@DataSource,其用于需要對個別方法指定其要使用的數據源(如某個讀操作需要在master上執行,但另一讀方法b需要在讀數據源的具體一臺上面執行)

              @Retention(RetentionPolicy.RUNTIME)

              @Target(ElementType.METHOD)

              public @interface DataSource {

              /**

              * 類型,代表是使用讀還是寫

              * @return

              */

              DataSourceType type() default DataSourceType.WRITE;

              /**

              * 指定要使用的DataSource的名稱

              * @return

              */

              String name() default "";

              }

              定義數據源類型,分為兩種:READ,WRITE,內容如下:

              public enum DataSourceType {

              READ, WRITE;

              }

              定義保存這此共享信息的類DynamicDataSourceHolder,在其中定義了兩個ThreadLocal和一個map,holder用于保存當前線程的數據源類型(讀或者寫),pool用于保存數據源名稱(如果指定),其內容如下:

              import java.util.Map;

              import java.util.concurrent.ConcurrentHashMap;

              public class DynamicDataSourceHolder {

              private static final Map<String, DataSourceType> cache = new ConcurrentHashMap<>();

              private static final ThreadLocal<DataSourceType> holder = new ThreadLocal<>();

              private static final ThreadLocal<String> 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();

              }

              }

              動態數據源類為DynamicDataSoruce,其繼承自AbstractRoutingDataSource,可以根據返回的key切換到相應的數據源,其內容如下:

              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 List<DataSource> readDataSource;

              private int readDataSourceSize;

              private Map<String, String> dataSourceMapping = new ConcurrentHashMap<>();

              @Override

              public void afterPropertiesSet() {

              if (this.writeDataSource == null) {

              throw new IllegalArgumentException("Property 'writeDataSource' is required");

              }

              setDefaultTargetDataSource(writeDataSource);

              Map<Object, Object> targetDataSource = new HashMap<>();

              targetDataSource.put(DataSourceType.WRITE.name(), writeDataSource);

              String poolName = ((HikariDataSource)writeDataSource).getPoolName();

              if (poolName != null && poolName.length() > 0) {

              dataSourceMapping.put(poolName,DataSourceType.WRITE.name());

              }

              if (this.readDataSource == null) {

              readDataSourceSize = 0;

              } else {

              for (int i = 0; i < readDataSource.size(); i++) {

              targetDataSource.put(DataSourceType.READ.name() + i, readDataSource.get(i));

              poolName = ((HikariDataSource)readDataSource.get(i)).getPoolName();

              if (poolName != null && poolName.length() > 0) {

              dataSourceMapping.put(poolName,DataSourceType.READ.name() + i);

              }

              }

              readDataSourceSize = readDataSource.size();

              }

              setTargetDataSources(targetDataSource);

              super.afterPropertiesSet();

              }

              @Override

              protected Object determineCurrentLookupKey() {

              DataSourceType dataSourceType = DynamicDataSourceHolder.getDataSource();

              String dataSourceName = null;

              if (dataSourceType == null ||dataSourceType == DataSourceType.WRITE || readDataSourceSize == 0) {

              dataSourceName = DataSourceType.WRITE.name();

              } else {

              String poolName = DynamicDataSourceHolder.getPoolName();

              if (poolName == null) {

              int idx = ThreadLocalRandom.current().nextInt(0, readDataSourceSize);

              dataSourceName = DataSourceType.READ.name() + idx;

              } else {

              dataSourceName = dataSourceMapping.get(poolName);

              }

              }

              DynamicDataSourceHolder.clearDataSource();

              return dataSourceName;

              }

              public void setWriteDataSource(DataSource writeDataSource) {

              this.writeDataSource = writeDataSource;

              }

              public void setReadDataSource(List<DataSource> readDataSource) {

              this.readDataSource = readDataSource;

              }

              }

              3.AOP攔截

              如果在相應的dao層做了自定義配置(指定數據源),則在些處理。解析相應方法上的@DataSource注解,如果存在,并把相應的信息保存至上面的DynamicDataSourceHolder中。在此對com.hfjy.service.order.dao包進行做攔截。內容如下:

              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攔截,對需要特殊方法可以指定要使用的數據源名稱(對應為連接池名稱)

              */

              @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層沒有指定相應的要使用的數據源,則在此進行攔截,根據是更新還是查詢設置數據源的類型,內容如下:

              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要使用的內容及DataSource,內容如下:

              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();

              }

              }

              如果不清楚,可以查看github上源碼orderdemo


            【Spring+MyBatis數據讀寫分離的實例詳解】相關文章:

            C語言以數據塊的形式讀寫文件實例代碼10-09

            如何實現yii2 數據庫讀寫分離配置07-01

            Java內部類詳解及實例分析06-25

            php數據類型詳解09-24

            php多個文件及圖片上傳實例詳解08-02

            C++類中的繼承實例詳解07-05

            C++冒泡排序算法實例詳解06-09

            C語言循環隊列的表示與實例詳解08-21

            詳解C語言格式化讀寫文件08-29

                    <pre id="bbfd9"><del id="bbfd9"><dfn id="bbfd9"></dfn></del></pre>

                    <ruby id="bbfd9"></ruby><p id="bbfd9"><mark id="bbfd9"></mark></p>

                    <p id="bbfd9"></p>

                    <p id="bbfd9"><cite id="bbfd9"></cite></p>

                      <th id="bbfd9"><form id="bbfd9"><dl id="bbfd9"></dl></form></th>

                      <p id="bbfd9"><cite id="bbfd9"></cite></p><p id="bbfd9"></p>
                      <p id="bbfd9"><cite id="bbfd9"><progress id="bbfd9"></progress></cite></p>
                      飘沙影院