多數(shù)據(jù)源怎么利用springboot進行配置-創(chuàng)新互聯(lián)

本篇文章給大家分享的是有關多數(shù)據(jù)源怎么利用spring boot進行配置,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

創(chuàng)新互聯(lián)-專業(yè)網站定制、快速模板網站建設、高性價比大連網站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式大連網站制作公司更省心,省錢,快速模板網站建設找我們,業(yè)務覆蓋大連地區(qū)。費用合理售后完善,十多年實體公司更值得信賴。

多數(shù)據(jù)源配置

創(chuàng)建一個Spring配置類,定義兩個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();
  }
}

對應的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支持

對JdbcTemplate的支持比較簡單,只需要為其注入對應的datasource即可,如下例子,在創(chuàng)建JdbcTemplate的時候分別注入名為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);
}

接下來通過測試用例來演示如何使用這兩個針對不同數(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 {
    // 往第一個數(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);
    // 往第二個數(shù)據(jù)源中插入一條數(shù)據(jù),若插入的是第一個數(shù)據(jù)源,則會主鍵沖突報錯
    jdbcTemplate2.update("insert into user(id,name,age) values(?, ?, ?)", 1, "aaa", 20);
    // 查一下第一個數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗證插入是否成功
    Assert.assertEquals("2", jdbcTemplate1.queryForObject("select count(1) from user", String.class));
    // 查一下第一個數(shù)據(jù)源中是否有兩條數(shù)據(jù),驗證插入是否成功
    Assert.assertEquals("1", jdbcTemplate2.queryForObject("select count(1) from user", String.class));
  }
}

完整示例:Chapter3-2-3

Spring-data-jpa支持

對于數(shù)據(jù)源的配置可以沿用上例中DataSourceConfig的實現(xiàn)。

新增對第一數(shù)據(jù)源的JPA配置,注意兩處注釋的地方,用于指定數(shù)據(jù)源對應的Entity實體和Repository定義位置,用@Primary區(qū)分主數(shù)據(jù)源。

新增對第二數(shù)據(jù)源的JPA配置,內容與第一數(shù)據(jù)源類似,具體如下:

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef="entityManagerFactorySecondary",
    transactionManagerRef="transactionManagerSecondary",
    basePackages= { "com.didispace.domain.s" }) //設置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") //設置實體類所在位置
        .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ù)據(jù)訪問對象位于:com.didispace.domain.p,次數(shù)據(jù)源的實體和數(shù)據(jù)訪問接口位于:com.didispace.domain.s。

分別在這兩個package下創(chuàng)建各自的實體和數(shù)據(jù)訪問接口

主數(shù)據(jù)源下,創(chuàng)建User實體和對應的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實體和對應的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> {
}

接下來通過測試用例來驗證使用這兩個針對不同數(shù)據(jù)源的配置進行數(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());
  }
}

以上就是多數(shù)據(jù)源怎么利用spring boot進行配置,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網站標題:多數(shù)據(jù)源怎么利用springboot進行配置-創(chuàng)新互聯(lián)
網頁鏈接:http://www.muchs.cn/article0/pisio.html

成都網站建設公司_創(chuàng)新互聯(lián),為您提供靜態(tài)網站、品牌網站設計企業(yè)網站制作、網站設計公司、品牌網站建設、電子商務

廣告

聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網站網頁設計