日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

学习Spring Boot:(二十四)多数据源配置与使用

發(fā)布時(shí)間:2025/3/12 javascript 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 学习Spring Boot:(二十四)多数据源配置与使用 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

隨著業(yè)務(wù)量增大,可能有些業(yè)務(wù)不是放在同一個(gè)數(shù)據(jù)庫(kù)中,所以系統(tǒng)有需求使用多個(gè)數(shù)據(jù)庫(kù)完成業(yè)務(wù)需求,我們需要配置多個(gè)數(shù)據(jù)源,從而進(jìn)行操作不同數(shù)據(jù)庫(kù)中數(shù)據(jù)。

正文

JdbcTemplate 多數(shù)據(jù)源

配置

需要在 Spring Boot 中配置多個(gè)數(shù)據(jù)庫(kù)連接,當(dāng)然怎么設(shè)置連接參數(shù)的 key 可以自己決定,

需要注意的是 Spring Boot 2.0 的默認(rèn)連接池配置參數(shù)好像有點(diǎn)問(wèn)題,由于默認(rèn)連接池已從 Tomcat 更改為 HikariCP,以前有一個(gè)參數(shù) url,已經(jīng)改成 hikari.jdbcUrl ,不然無(wú)法注冊(cè)。我下面使用的版本是 1.5.9。

server:port: 8022 spring:datasource:url: jdbc:mysql://localhost:3306/learn?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driversecond-datasource:url: jdbc:mysql://localhost:3306/learn1?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123457driver-class-name: com.mysql.jdbc.Driver
注冊(cè) DataSource

注冊(cè)兩個(gè)數(shù)據(jù)源,分別注冊(cè)兩個(gè) JdbcTemplate,

@Configuration public class DataSourceConfig {/*** 注冊(cè) data source** @return*/@ConfigurationProperties(prefix = "spring.datasource")@Bean("firstDataSource")@Primary // 有相同實(shí)例優(yōu)先選擇public DataSource firstDataSource() {return DataSourceBuilder.create().build();}@ConfigurationProperties(prefix = "spring.second-datasource")@Bean("secondDataSource")public DataSource secondDataSource() {return DataSourceBuilder.create().build();}@Bean("firstJdbcTemplate")@Primarypublic JdbcTemplate firstJdbcTemplate(DataSource dataSource) {return new JdbcTemplate(dataSource);}@Bean("secondJdbcTemplate")public JdbcTemplate secondJdbcTemplate(@Qualifier("secondDataSource") DataSource dataSource) {return new JdbcTemplate(dataSource);} }
測(cè)試
@SpringBootTest @RunWith(SpringRunner.class) public class TestJDBC {@Autowiredprivate JdbcTemplate jdbcTemplate;@Autowired@Qualifier("secondJdbcTemplate")private JdbcTemplate jdbcTemplate1;@Beforepublic void before() {jdbcTemplate.update("DELETE FROM employee");jdbcTemplate1.update("DELETE FROM employee");}@Testpublic void testJDBC() {jdbcTemplate.update("insert into employee(id,name,age) VALUES (1, 'wuwii', 24)");jdbcTemplate1.update("insert into employee(id,name,age) VALUES (1, 'kronchan', 23)");Assert.assertThat("wuwii", Matchers.equalTo(jdbcTemplate.queryForObject("SELECT name FROM employee WHERE id=1", String.class)));Assert.assertThat("kronchan", Matchers.equalTo(jdbcTemplate1.queryForObject("SELECT name FROM employee WHERE id=1", String.class)));} }

使用 JPA 支持多數(shù)據(jù)源

配置

相比使用 jdbcTemplate,需要設(shè)置下 JPA 的相關(guān)參數(shù)即可,沒(méi)多大變化:

server:port: 8022 spring:datasource:url: jdbc:mysql://localhost:3306/learn?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driversecond-datasource:url: jdbc:mysql://localhost:3306/learn1?useSSL=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8username: rootpassword: 123456driver-class-name: com.mysql.jdbc.Driverjpa:show-sql: truedatabase: mysqlhibernate:# update 更新表結(jié)構(gòu)# create 每次啟動(dòng)刪除上次表,再創(chuàng)建表,會(huì)造成數(shù)據(jù)丟失# create-drop: 每次加載hibernate時(shí)根據(jù)model類(lèi)生成表,但是sessionFactory一關(guān)閉,表就自動(dòng)刪除。# validate :每次加載hibernate時(shí),驗(yàn)證創(chuàng)建數(shù)據(jù)庫(kù)表結(jié)構(gòu),只會(huì)和數(shù)據(jù)庫(kù)中的表進(jìn)行比較,不會(huì)創(chuàng)建新表,但是會(huì)插入新值。ddl-auto: updateproperties:hibernate:dialect: org.hibernate.dialect.MySQLDialect

首先一樣的是我們要注冊(cè)相應(yīng)的 DataSource,還需要指定相應(yīng)的數(shù)據(jù)源所對(duì)應(yīng)的實(shí)體類(lèi)和數(shù)據(jù)操作層 Repository的位置:
* firstDataSource

@Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "firstEntityManagerFactory",transactionManagerRef = "firstTransactionManager",basePackages = "com.wuwii.module.system.dao" // 設(shè)置該數(shù)據(jù)源對(duì)應(yīng) dao 層所在的位置 ) public class FirstDataSourceConfig {@Autowiredprivate JpaProperties jpaProperties;@Primary@Bean(name = "firstEntityManager")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary(builder).getObject().createEntityManager();}@ConfigurationProperties(prefix = "spring.datasource")@Bean("firstDataSource")@Primary // 有相同實(shí)例優(yōu)先選擇,相同實(shí)例只能設(shè)置唯一public DataSource firstDataSource() {return DataSourceBuilder.create().build();}@Primary@Bean(name = "firstEntityManagerFactory")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {return builder.dataSource(firstDataSource()).properties(getVendorProperties(firstDataSource())).packages("com.wuwii.module.system.entity") //設(shè)置該數(shù)據(jù)源對(duì)應(yīng)的實(shí)體類(lèi)所在位置.persistenceUnit("firstPersistenceUnit").build();}private Map<String, String> getVendorProperties(DataSource dataSource) {return jpaProperties.getHibernateProperties(dataSource);}@Primary@Bean(name = "firstTransactionManager")public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());}}
  • secondDataSource:
@Configuration @EnableTransactionManagement @EnableJpaRepositories(entityManagerFactoryRef = "secondEntityManagerFactory",transactionManagerRef = "secondTransactionManager",basePackages = "com.wuwii.module.user.dao" // 設(shè)置該數(shù)據(jù)源 dao 層所在的位置 ) public class SecondDataSourceConfig {@Autowiredprivate JpaProperties jpaProperties;@Bean(name = "secondEntityManager")public EntityManager entityManager(EntityManagerFactoryBuilder builder) {return entityManagerFactoryPrimary(builder).getObject().createEntityManager();}@ConfigurationProperties(prefix = "spring.second-datasource")@Bean("secondDataSource")public DataSource secondDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "secondEntityManagerFactory")public LocalContainerEntityManagerFactoryBean entityManagerFactoryPrimary (EntityManagerFactoryBuilder builder) {return builder.dataSource(secondDataSource()).properties(getVendorProperties(secondDataSource())).packages("com.wuwii.module.user.entity") //設(shè)置該數(shù)據(jù)源鎖對(duì)應(yīng)的實(shí)體類(lèi)所在的位置.persistenceUnit("secondPersistenceUnit").build();}private Map<String, String> getVendorProperties(DataSource dataSource) {return jpaProperties.getHibernateProperties(dataSource);}@Bean(name = "secondTransactionManager")public PlatformTransactionManager transactionManagerPrimary(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryPrimary(builder).getObject());}}
測(cè)試
@SpringBootTest @RunWith(SpringRunner.class) public class TestDemo {@Autowiredprivate EmployeeDao employeeDao;@Autowiredprivate UserDao userDao;@Beforepublic void before() {employeeDao.deleteAll();userDao.deleteAll();}@Testpublic void test() {Employee employee = new Employee(null, "wuwii", 24);employeeDao.save(employee);User user = new User(null, "KronChan", 24);userDao.save(user);Assert.assertThat(employee, Matchers.equalTo(employeeDao.findOne(Example.of(employee))));Assert.assertThat(user, Matchers.equalTo(userDao.findOne(Example.of(user))));} } 創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)

總結(jié)

以上是生活随笔為你收集整理的学习Spring Boot:(二十四)多数据源配置与使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。