前言
最近接到一個新需求需要處理多數據源的問題 ,今天就來和大家一起學習一下。
一、使用步驟
1.引入庫
代碼如下(示例):
<!--配置多數據源--><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>3.5.0</version></dependency>
2.Springboot的application.yml中進行配置
代碼如下(示例):
datasource:dynamic:primary: master #設置默認的數據源或者數據源組,默認值即為masterstrict: false #嚴格匹配數據源,默認false. true未匹配到指定數據源時拋異常,false使用默認數據源datasource:master:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxx:3306/demo?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=trueusername: xxxpassword: xxxtest:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://xxx2:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true&allowPublicKeyRetrieval=trueusername: xxxpassword: xxx
配置了兩個數據源,master與test,其中選擇master作為默認數據源(對應primary(主要的)配置);
3. ServiceImpl層注解使用實例,可以注解在方法上或類上
1.類上注解
@Service
@Slf4j
@DS("test")//使用test數據源
public class TestServiceImpl implements TestService {@Resourceprivate TestMapper testMapper;@Overridepublic Integer saveTest(Test test) {return testMapper.insertTest(test);}
}
2.方法上注解(mapper上面也需要注解)
@Service
@Slf4j
public class TestServiceImpl implements TestService {@Resourceprivate TestMapper testMapper;@Override@DS("test")//使用test數據源public Integer saveTest(Test test) {return testMapper.insertTest(test);}
}
4. 配置啟動類
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@EnableScheduling
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class Application {public static void main(String[] args) {SinoApplication.single(ModuleInfo.ModuleName, Application.class, args);}
}
5. 配置Dockerfile文件
"-Dspring.datasource.dynamic.enabled=true",\
失效場景解決方案
使用動態數據源(@DS)時,@Transactional使用可能會照成@DS失效。
解決方案:
1.去掉事務(不建議)
2.@DS切換數據源的方法添加事務傳播屬性@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
3.去掉@DS切換數據源方法的事務,主方法用@DSTransactional注解。
總結
以上就是今天要講的內容,本文僅僅簡單介紹了@DS注解的使用