基本的に、インターネット上の記事には複数のデータソースのみまたは動的なデータソースのみがありますが、最近のプロジェクトは2つの方法を同時に使用する必要があります。参照の構成方法を記録しましょう。
アプリケーションシナリオ
このプロジェクトは、2つの異なるデータベースAとBを同時に接続する必要があり、どちらもマスタースレーブアーキテクチャ、1つの文書ライブラリ、複数の読み取りライブラリです。
複数のデータソース
まず、spring.datasourceを読み取るため、Spring Bootに付属するDataSourceAutoconfigurationを無効にする必要があります。 @springBootApplicationアノテーションに除外属性を追加するだけです。
@springBootApplication(exclude = {dataSourceautoconfiguration.class})public class titanwebapplication {public static void main(string [] args){springApplication.run(titanwebapplication.class、args); }}次に、Application.Propertiesでマルチデータソース接続情報を構成します。
#タイタン図書館spring.datasource.titan-master.url = jdbc:mysql:// xxxx:port/titan?charatereCoding = utf-8spring.datasource.titan-master.u sername = spring.datasource.titan-master.password = spring.datasource.titan-master.driver-class-name = com.mysql.jdbc.driver#接続プール構成#omit#その他のライブラリ spring.datasource.db2.url=jdbc:mysql://XXXX:port/titan2?characterEncoding=UTF-8spring.datasource.db2.username=spring.datasource.db2.password=spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
自動データソースの構成を無効にしているため、次のステップでこれらのデータソースを手動で作成する必要があります。
@configurationPublic class dataSourceconfig {@bean(name = "titanmasterds")@configurationproperties(prefix = "spring.datasource.titan-master")// application.properteis public datasource1() } @bean(name = "ds2")@configurationProperties(prefix = "spring.datasource.db2")// application.poperteis public datasource datasource2(){return datasourcebuilder.create()。 }}次に、さまざまなデータソースを使用するように、2つのMyBatis SQLSessionFactoryを構成する必要があります。
@configuration @mapperscan(basepackages = {"titan.mapper"}、sqlsessionfactoryref = "sqlsessionfactory1")public class mybatisdbaconfig {@autowired @qualifier( "titanmasterds")private datasource ds1; @bean public sqlsessionfactory sqlsessionfactory1()throws exception {sqlsessionfactorybean factorybean = new sqlsessionfactorybean(); Factorybean.setDataSource(DS1); // Titanデータソースを使用して、Titan Libraryを復活させるFactorybean.getObject()に接続します。 } @bean public sqlsessionTemplate sqlsessionTemplate1()Throws Exception {sqlSessionTemplate Template = new SQLSessionTemplate(SQLSessionFactory1()); //上記で構成された工場を使用してテンプレートを返します。 }}上記の構成の後、Titan.Mapperの下のMapperインターフェイスはTitanデータソースを使用します。同様に、2番目のSQLSessionFactoryを使用できます。
@configuration @mapperscan(basepackages = {"other.mapper"}、sqlsessionfactoryref = "sqlsessionfactory2")public class mybatisdbbconfig {@autowired @qualifier( "ds2")private datasource ds2; @bean public sqlsessionfactory sqlsessionfactory2()throws exception {sqlsessionfactorybean factorybean = new sqlsessionfactorybean(); Factorybean.setDataSource(DS2); return factorybean.getObject(); } @bean public sqlsessionTemplate sqlsessionTemplate2()Throws Exception {sqlSessionTemplate Template = new SQLSessionTemplate(sqlSessionFactory2());テンプレートを返します。 }}これらの構成を完了したら、2つのMapper Titan.mapper.usermapperおよびother.mapper.rolemapperがあるとします。前者を使用すると、タイタンライブラリが自動的に接続され、後者はDS2ライブラリに接続されます。
動的なデータソース
動的なデータソースを使用する当初の意図は、アプリケーションレイヤーで読み取りと書き込み、つまり、プログラムコードのさまざまなクエリメソッドを制御して、さまざまなライブラリに接続できることです。この方法に加えて、データベースミドルウェアも適しています。その利点は、データベースクラスターがアプリケーションのために単一のライブラリにのみ公開され、データソースのコードロジックを切り替える必要がないことです。
カスタムアノテーション + AOPを介した動的なデータソースの切り替えを実現します。
まず、ContexTholderを定義して、現在のスレッドで使用されるデータソース名を保存します。
パブリッククラスDataSourceContextholder {public static final logger log = loggerfactory.getLogger(dataSourceContextholder.class); / ***デフォルトデータソース*/ public static final string default_ds = "titan-master"; private static final threadlocal <string> contextholder = new threadlocal <>(); //データソース名public static void setdb(string dbtype){log.debug( "{} data source"、dbtype); contextholder.set(dbtype); } //データソース名を取得しますpublic static string getdb(){return(contextholder.get()); } //データソース名Public static void cleardb(){contextholder.remove(); }}次に、javax.sql.datasourceインターフェイスの実装をカスタマイズします。ここでは、Springが事前に実装した親クラスのAbstroutingDataSourceを継承するだけです。
パブリッククラスのdynamicdatasourceは、abstractroutingdatasourceを拡張します{private static final logger log = loggerfactory.getLogger(dynamicdatasource.class); @OverrideプロテクションオブジェクトsecienCurrentlookupkey(){log.debug( "data source is {}"、datasourcecontextholder.getdb()); DataSourceContextholder.getDb()を返します。 }}動的なデータソースを作成します:
/ ***ダイナミックデータソース:aop* @return*/ @bean(name = "dynamicds1")public datasource datasource(){dynamicdatasource dynamicdatasource = new dynamicdatasource(); //デフォルトのデータソースDynamicDataSource.setDefaultTargetDataSource(dataSource1()); //マルチデータソースマップ<オブジェクト、オブジェクト> dsmap = new Hashmap(5); dsmap.put( "titan-master"、dataSource1()); dsmap.put( "ds2"、dataSource2()); dynamicdatasource.settargetdatasources(dsmap); DynamicDataSourceを返します。 }カスタムAnnotation @DSは、エンコード時に使用するメソッドが使用するデータソースを指定するために使用されます。
@retention(RetentionPolicy.Runtime)@Target({elementType.Method})public @interface ds {string value()default "titan-master";}スイッチングロジックを実装するには、AOPセクションを記述します。
@aspey@componentpublic class dynamicdatasourceaspect {@before( "@annotation(ds)")public void beforeswitchds(joinpoint point){//現在のアクセスクラスclass <?> classname = point.getTarget()。 //アクセスメソッド名name string methodname = point.getSignature()。getName(); //メソッドクラスのパラメーターのタイプを取得[] argclass =((methodignature)point.getSignature())。getParametertypes();文字列dataSource = datasourcecontextholder.default_ds; try {//アクセスされたメソッドオブジェクトはmethod method = classname.getMethod(methodname、argclass)です。 // @DSアノテーションが存在するかどうかを判断します。 // annotation dataSource = annotation.value()でデータソース名を取り出します。 }} catch(例外e){e.printstacktrace(); } //データソースDataSourceContextholder.setdb(dataSource)を切り替えます。 } @after( " @annotation(ds)")public void afterswitchds(joinpoint point){datasourcecontextholder.cleardb(); }}上記の構成を完了した後、以前のsqlSessionFactory構成でDynamicDataSourceを指定して、DynamicDataSourceを使用してサービス内のデータソースを喜んで切り替えます。
@autowired private useramodelmapper useramapper; @DS( "Titan-Master")public String ds1(){return useramapper.selectbyprimarykey(1).getname(); } @ds( "ds2")public string ds2(){return useramapper.selectbyprimarykey(1).getname(); }要約します
上記は、編集者が紹介したSpring Boot + MyBatis Multi-Dataソースと動的データソース構成方法です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!