詳解spring boot實(shí)現(xiàn)多數(shù)據(jù)源代碼實(shí)戰(zhàn)
之前在介紹使用JdbcTemplate和Spring-data-jpa時(shí),都使用了單數(shù)據(jù)源。在單數(shù)據(jù)源的情況下,Spring Boot的配置非常簡(jiǎn)單,只需要在application.properties文件中配置連接參數(shù)即可。但是往往隨著業(yè)務(wù)量發(fā)展,我們通常會(huì)進(jìn)行數(shù)據(jù)庫拆分或是引入其他數(shù)據(jù)庫,從而我們需要配置多個(gè)數(shù)據(jù)源,下面基于之前的JdbcTemplate和Spring-data-jpa例子分別介紹兩種多數(shù)據(jù)源的配置方式。
多數(shù)據(jù)源配置
創(chuàng)建一個(gè)Spring配置類,定義兩個(gè)DataSource用來讀取application.properties中的不同配置。如下例子中,主數(shù)據(jù)源配置為spring.datasource.primary開頭的配置,第二數(shù)據(jù)源配置為spring.datasource.secondary開頭的配置。
@Configuration
public class DataSourceConfig {
@Bean(name = "primaryDataSource")
@Qualifier("primaryDataSource")
@ConfigurationProperties(prefix="spring.datasource.primary")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryDataSource")
@Qualifier("secondaryDataSource")
@Primary
@ConfigurationProperties(prefix="spring.datasource.secondary")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
}
對(duì)應(yīng)的application.properties配置如下:
spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1 spring.datasource.primary.username=root spring.datasource.primary.password=root spring.datasource.primary.driver-class-name=com.mysql.jdbc.Driver spring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2 spring.datasource.secondary.username=root spring.datasource.secondary.password=root spring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver
JdbcTemplate支持
對(duì)JdbcTemplate的支持比較簡(jiǎn)單,只需要為其注入對(duì)應(yīng)的datasource即可,如下例子,在創(chuàng)建JdbcTemplate的時(shí)候分別注入名為primaryDataSource和secondaryDataSource的數(shù)據(jù)源來區(qū)分不同的JdbcTemplate。
@Bean(name = "primaryJdbcTemplate")
public JdbcTemplate primaryJdbcTemplate(
@Qualifier("primaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean(name = "secondaryJdbcTemplate")
public JdbcTemplate secondaryJdbcTemplate(
@Qualifier("secondaryDataSource") DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
接下來通過測(cè)試用例來演示如何使用這兩個(gè)針對(duì)不同數(shù)據(jù)源的JdbcTemplate。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
@Autowired
@Qualifier("primaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate1;
@Autowired
@Qualifier("secondaryJdbcTemplate")
protected JdbcTemplate jdbcTemplate2;
@Before
public void setUp() {
jdbcTemplate1.update("DELETE FROM USER ");
jdbcTemplate2.update("DELETE FROM USER ");
}
@Test
public void test() throws Exception {
// 往第一個(gè)數(shù)據(jù)源中插入兩條數(shù)據(jù)
jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
jdbcTemplate1.update("insert into user(id,name,age) values(?, ?, ?)", 2, "bbb", 30);
// 往第二個(gè)數(shù)據(jù)源中插入一條數(shù)據(jù),若插入的是第一個(gè)數(shù)據(jù)源,則會(huì)主鍵沖突報(bào)錯(cuò)
jdbcTemplate2.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
// 查一下第一個(gè)數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗(yàn)證插入是否成功
Assert.assertEquals("2", jdbcTemplate1.queryForObject("select count(1) from user", String.class));
// 查一下第一個(gè)數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗(yàn)證插入是否成功
Assert.assertEquals("1", jdbcTemplate2.queryForObject("select count(1) from user", String.class));
}
}
完整示例:Chapter3-2-3
Spring-data-jpa支持
對(duì)于數(shù)據(jù)源的配置可以沿用上例中DataSourceConfig的實(shí)現(xiàn)。
新增對(duì)第一數(shù)據(jù)源的JPA配置,注意兩處注釋的地方,用于指定數(shù)據(jù)源對(duì)應(yīng)的Entity實(shí)體和Repository定義位置,用@Primary區(qū)分主數(shù)據(jù)源。
新增對(duì)第二數(shù)據(jù)源的JPA配置,內(nèi)容與第一數(shù)據(jù)源類似,具體如下:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef="entityManagerFactorySecondary",
transactionManagerRef="transactionManagerSecondary",
basePackages= { "com.didispace.domain.s" }) //設(shè)置Repository所在位置
public class SecondaryConfig {
@Autowired @Qualifier("secondaryDataSource")
private DataSource secondaryDataSource;
@Bean(name = "entityManagerSecondary")
public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
return entityManagerFactorySecondary(builder).getObject().createEntityManager();
}
@Bean(name = "entityManagerFactorySecondary")
public LocalContainerEntityManagerFactoryBean entityManagerFactorySecondary (EntityManagerFactoryBuilder builder) {
return builder
.dataSource(secondaryDataSource)
.properties(getVendorProperties(secondaryDataSource))
.packages("com.didispace.domain.s") //設(shè)置實(shí)體類所在位置
.persistenceUnit("secondaryPersistenceUnit")
.build();
}
@Autowired
private JpaProperties jpaProperties;
private Map<String, String> getVendorProperties(DataSource dataSource) {
return jpaProperties.getHibernateProperties(dataSource);
}
@Bean(name = "transactionManagerSecondary")
PlatformTransactionManager transactionManagerSecondary(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactorySecondary(builder).getObject());
}
}
完成了以上配置之后,主數(shù)據(jù)源的實(shí)體和數(shù)據(jù)訪問對(duì)象位于:com.didispace.domain.p,次數(shù)據(jù)源的實(shí)體和數(shù)據(jù)訪問接口位于:com.didispace.domain.s。
分別在這兩個(gè)package下創(chuàng)建各自的實(shí)體和數(shù)據(jù)訪問接口
主數(shù)據(jù)源下,創(chuàng)建User實(shí)體和對(duì)應(yīng)的Repository接口
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private Integer age;
public User(){}
public User(String name, Integer age) {
this.name = name;
this.age = age;
}
// 省略getter、setter
}
public interface UserRepository extends JpaRepository<User, Long> {
}
從數(shù)據(jù)源下,創(chuàng)建Message實(shí)體和對(duì)應(yīng)的Repository接口
@Entity
public class Message {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String name;
@Column(nullable = false)
private String content;
public Message(){}
public Message(String name, String content) {
this.name = name;
this.content = content;
}
// 省略getter、setter
}
public interface MessageRepository extends JpaRepository<Message, Long> {
}
接下來通過測(cè)試用例來驗(yàn)證使用這兩個(gè)針對(duì)不同數(shù)據(jù)源的配置進(jìn)行數(shù)據(jù)操作。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
public class ApplicationTests {
@Autowired
private UserRepository userRepository;
@Autowired
private MessageRepository messageRepository;
@Test
public void test() throws Exception {
userRepository.save(new User("aaa", 10));
userRepository.save(new User("bbb", 20));
userRepository.save(new User("ccc", 30));
userRepository.save(new User("ddd", 40));
userRepository.save(new User("eee", 50));
Assert.assertEquals(5, userRepository.findAll().size());
messageRepository.save(new Message("o1", "aaaaaaaaaa"));
messageRepository.save(new Message("o2", "bbbbbbbbbb"));
messageRepository.save(new Message("o3", "cccccccccc"));
Assert.assertEquals(3, messageRepository.findAll().size());
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于SpringBoot中Ajax跨域以及Cookie無法獲取丟失問題
這篇文章主要介紹了關(guān)于SpringBoot中Ajax跨域以及Cookie無法獲取丟失問題,本文具有參考意義,遇到相同或者類似問題的小伙伴希望可以從中找到靈感2023-03-03
spring設(shè)置定時(shí)任務(wù)方式(@Scheduled)
這篇文章主要介紹了spring設(shè)置定時(shí)任務(wù)方式(@Scheduled),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
Spring?myBatis數(shù)據(jù)庫連接異常問題及解決
這篇文章主要介紹了Spring?myBatis數(shù)據(jù)庫連接異常問題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
SpringBoot使用Kafka來優(yōu)化接口請(qǐng)求的并發(fā)方式
這篇文章主要介紹了SpringBoot使用Kafka來優(yōu)化接口請(qǐng)求的并發(fā)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07
Spring Boot 單元測(cè)試和集成測(cè)試實(shí)現(xiàn)詳解
這篇文章主要介紹了Spring Boot 單元測(cè)試和集成測(cè)試實(shí)現(xiàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
Java利用poi實(shí)現(xiàn)word表格轉(zhuǎn)excel
這篇文章主要為大家詳細(xì)介紹了Java如何利用poi實(shí)現(xiàn)word表格轉(zhuǎn)excel,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-03-03
JavaWeb ServletConfig作用及原理分析講解
ServletConfig對(duì)象,叫Servlet配置對(duì)象。主要用于加載配置文件的初始化參數(shù)。我們知道一個(gè)Web應(yīng)用里面可以有多個(gè)servlet,如果現(xiàn)在有一份數(shù)據(jù)需要傳給所有的servlet使用,那么我們就可以使用ServletContext對(duì)象了2022-10-10

