欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在SpringBoot微服務(wù)中設(shè)置和管理多個(gè)數(shù)據(jù)庫(kù)的代碼示例

 更新時(shí)間:2024年12月26日 09:12:30   作者:小蝸牛慢慢爬行  
在現(xiàn)代微服務(wù)架構(gòu)中,通常需要與多個(gè)數(shù)據(jù)庫(kù)交互的服務(wù),這可能是由于各種原因,例如遺留系統(tǒng)集成、不同類型的數(shù)據(jù)存儲(chǔ)需求,或者僅僅是為了優(yōu)化性能,在本綜合指南中,我們將探討如何在 Spring Boot 微服務(wù)中設(shè)置和管理多個(gè)數(shù)據(jù)庫(kù)連接,需要的朋友可以參考下

引言

在現(xiàn)代微服務(wù)架構(gòu)中,通常需要與多個(gè)數(shù)據(jù)庫(kù)交互的服務(wù)。這可能是由于各種原因,例如遺留系統(tǒng)集成、不同類型的數(shù)據(jù)存儲(chǔ)需求,或者僅僅是為了優(yōu)化性能。Spring Boot 具有靈活的配置和強(qiáng)大的數(shù)據(jù)訪問(wèn)庫(kù),可以輕松配置多個(gè)數(shù)據(jù)庫(kù)。在本綜合指南中,我們將探討如何在 Spring Boot 微服務(wù)中設(shè)置和管理多個(gè)數(shù)據(jù)庫(kù)連接。

1. 簡(jiǎn)介

微服務(wù)通常需要與各種數(shù)據(jù)庫(kù)交互。每個(gè)微服務(wù)可能需要不同類型的數(shù)據(jù)庫(kù),例如用于事務(wù)數(shù)據(jù)的 SQL 數(shù)據(jù)庫(kù)和用于非結(jié)構(gòu)化數(shù)據(jù)的 NoSQL 數(shù)據(jù)庫(kù)。Spring Boot 為配置和管理多個(gè)數(shù)據(jù)源提供了出色的支持,使其成為現(xiàn)代微服務(wù)架構(gòu)的理想選擇。

2.為什么要使用多個(gè)數(shù)據(jù)庫(kù)?

您可能需要在微服務(wù)中使用多個(gè)數(shù)據(jù)庫(kù)的原因如下:

  • 遺留系統(tǒng)集成:與遺留系統(tǒng)的現(xiàn)有數(shù)據(jù)庫(kù)集成。
  • 優(yōu)化性能:使用針對(duì)特定類型的數(shù)據(jù)(例如關(guān)系型與非關(guān)系型)優(yōu)化的不同數(shù)據(jù)庫(kù)。
  • 數(shù)據(jù)隔離:出于安全、合規(guī)或組織原因分離數(shù)據(jù)。
  • 可擴(kuò)展性:在不同的數(shù)據(jù)庫(kù)之間分配數(shù)據(jù)負(fù)載以提高性能。

3.設(shè)置 Spring Boot 項(xiàng)目

首先,創(chuàng)建一個(gè)新的 Spring Boot 項(xiàng)目。您可以使用 Spring Initializr 或您喜歡的 IDE 來(lái)設(shè)置項(xiàng)目。

Maven 依賴項(xiàng)

在您的 中pom.xml包含 Spring Data JPA 和您將使用的數(shù)據(jù)庫(kù)的依賴項(xiàng)(例如,內(nèi)存中的 H2、PostgreSQL、MySQL 等)。

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>

4.配置多個(gè)數(shù)據(jù)源

application.ymlapplication.properties文件中,配置每個(gè)數(shù)據(jù)庫(kù)的連接屬性。

application.yml

spring:
  datasource:
    primary:
      url: jdbc:h2:mem:primarydb
      driver-class-name: org.h2.Driver
      username: sa
      password: password
    secondary:
      url: jdbc:postgresql://localhost:5432/secondarydb
      driver-class-name: org.postgresql.Driver
      username: postgres
      password: password
jpa:
    primary:
      database-platform: org.hibernate.dialect.H2Dialect
      hibernate:
        ddl-auto: update
    secondary:
      database-platform: org.hibernate.dialect.PostgreSQLDialect
      hibernate:
        ddl-auto: update

5.創(chuàng)建數(shù)據(jù)源配置類

接下來(lái),為每個(gè)數(shù)據(jù)源創(chuàng)建單獨(dú)的配置類。

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

package com.example.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.primary.repository",
    entityManagerFactoryRef = "primaryEntityManagerFactory",
    transactionManagerRef = "primaryTransactionManager"
)
public class PrimaryDataSourceConfig {
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "primaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean primaryEntityManagerFactory(
            @Qualifier("primaryDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan(new String[] { "com.example.primary.entity" });
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        return em;
    }
    @Bean(name = "primaryTransactionManager")
    public PlatformTransactionManager primaryTransactionManager(
            @Qualifier("primaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

輔助數(shù)據(jù)源配置

package com.example.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
@Configuration
@EnableJpaRepositories(
    basePackages = "com.example.secondary.repository",
    entityManagerFactoryRef = "secondaryEntityManagerFactory",
    transactionManagerRef = "secondaryTransactionManager"
)
public class SecondaryDataSourceConfig {
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "secondaryEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean secondaryEntityManagerFactory(
            @Qualifier("secondaryDataSource") DataSource dataSource) {
        LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
        em.setDataSource(dataSource);
        em.setPackagesToScan(new String[] { "com.example.secondary.entity" });
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        em.setJpaVendorAdapter(vendorAdapter);
        return em;
    }
    @Bean(name = "secondaryTransactionManager")
    public PlatformTransactionManager secondaryTransactionManager(
            @Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

6. 定義實(shí)體管理器

為每個(gè)數(shù)據(jù)庫(kù)定義實(shí)體類。確保將它們放在配置類中指定的相應(yīng)包中。

主數(shù)據(jù)庫(kù)實(shí)體

package com.example.primary.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class PrimaryEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    // getters and setters
}

輔助數(shù)據(jù)庫(kù)實(shí)體

package com.example.secondary.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class SecondaryEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String description;
    // getters and setters
}

7. 創(chuàng)建存儲(chǔ)庫(kù)

為每個(gè)數(shù)據(jù)庫(kù)創(chuàng)建存儲(chǔ)庫(kù)接口,確保它們按照配置放置在正確的包中。

主存儲(chǔ)庫(kù)

package com.example.primary.repository;
import com.example.secondary.entity.SecondaryEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SecondaryRepository extends JpaRepository<SecondaryEntity, Long> {
}

二級(jí)存儲(chǔ)庫(kù)

package com.example.secondary.repository;
import com.example.secondary.entity.SecondaryEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SecondaryRepository extends JpaRepository<SecondaryEntity, Long> {
}

8.測(cè)試配置

最后,創(chuàng)建一個(gè)簡(jiǎn)單的 REST 控制器來(lái)測(cè)試設(shè)置。此控制器將使用兩個(gè)存儲(chǔ)庫(kù)來(lái)執(zhí)行 CRUD 操作。

package com.example.controller;
import com.example.primary.entity.PrimaryEntity;
import com.example.primary.repository.PrimaryRepository;
import com.example.secondary.entity.SecondaryEntity;
import com.example.secondary.repository.SecondaryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
    @Autowired
    private PrimaryRepository primaryRepository;
    @Autowired
    private SecondaryRepository secondaryRepository;
    @GetMapping("/test")
    public String test() {
        PrimaryEntity primaryEntity = new PrimaryEntity();
        primaryEntity.setName("Primary Entity");
        primaryRepository.save(primaryEntity);
        SecondaryEntity secondaryEntity = new SecondaryEntity();
        secondaryEntity.setDescription("Secondary Entity");
        secondaryRepository.save(secondaryEntity);
        return "Entities saved!";
    }
}

以上就是在SpringBoot微服務(wù)中設(shè)置和管理多個(gè)數(shù)據(jù)庫(kù)的代碼示例的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot微服務(wù)設(shè)置和管理數(shù)據(jù)庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論