亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

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

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

引言

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

1. 簡介

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

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

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

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

3.設置 Spring Boot 項目

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

Maven 依賴項

在您的 中pom.xml包含 Spring Data JPA 和您將使用的數(shù)據(jù)庫的依賴項(例如,內(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.配置多個數(shù)據(jù)源

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

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ù)源配置類

接下來,為每個數(shù)據(jù)源創(chuàng)建單獨的配置類。

主數(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ù)據(jù)庫定義實體類。確保將它們放在配置類中指定的相應包中。

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

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ù)庫實體

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)建存儲庫

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

主存儲庫

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> {
}

二級存儲庫

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.測試配置

最后,創(chuàng)建一個簡單的 REST 控制器來測試設置。此控制器將使用兩個存儲庫來執(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微服務中設置和管理多個數(shù)據(jù)庫的代碼示例的詳細內(nèi)容,更多關于SpringBoot微服務設置和管理數(shù)據(jù)庫的資料請關注腳本之家其它相關文章!

相關文章

  • Mybatis-Plus的應用場景描述及注入SQL原理分析

    Mybatis-Plus的應用場景描述及注入SQL原理分析

    MyBatis-Plus是一個 MyBatis 的增強工具,在 MyBatis 的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生,本文重點給大家介紹Mybatis-Plus的應用場景及注入SQL原理分析,感興趣的朋友跟隨小編一起學習吧
    2021-05-05
  • hadoop運行java程序(jar包)并運行時動態(tài)指定參數(shù)

    hadoop運行java程序(jar包)并運行時動態(tài)指定參數(shù)

    這篇文章主要介紹了hadoop如何運行java程序(jar包)并運行時動態(tài)指定參數(shù),使用hadoop 運行 java jar包,Main函數(shù)一定要加上全限定類名,需要的朋友可以參考下
    2021-06-06
  • SpringBoot+MinIO實現(xiàn)對象存儲的示例詳解

    SpringBoot+MinIO實現(xiàn)對象存儲的示例詳解

    MinIO?是一個基于Apache?License?v2.0開源協(xié)議的對象存儲服務,它是一個非常輕量的服務,可以很簡單的和其他應用的結(jié)合,所以下面我們就來看看SpringBoot如何整合MinIO實現(xiàn)對象存儲吧
    2023-10-10
  • Spring+SpringMVC+MyBatis深入學習及搭建(二)之MyBatis原始Dao開發(fā)和mapper代理開發(fā)

    Spring+SpringMVC+MyBatis深入學習及搭建(二)之MyBatis原始Dao開發(fā)和mapper代理開發(fā)

    這篇文章主要介紹了Spring+SpringMVC+MyBatis深入學習及搭建(二)之MyBatis原始Dao開發(fā)和mapper代理開發(fā),需要的朋友可以參考下
    2017-05-05
  • Java中的泛型詳細解析

    Java中的泛型詳細解析

    這篇文章主要介紹了Java中的泛型詳細解析,泛型又稱參數(shù)化類型,是JDK5.0出現(xiàn)的新特性,解決了數(shù)據(jù)類型的安全型問題,Java泛型可以保證如果程序在編譯時沒用發(fā)出警告,運行時就不會產(chǎn)生classCastException異常,需要的朋友可以參考下
    2024-01-01
  • java Iterator.remove()實例方法分析

    java Iterator.remove()實例方法分析

    在本篇文章里小編給大家整理了一篇關于java Iterator.remove()實例方法分析,有興趣的朋友們跟著學習下。
    2021-01-01
  • 深度理解Java中volatile的內(nèi)存語義

    深度理解Java中volatile的內(nèi)存語義

    前面我們已經(jīng)講過了volatile的作用、底層實現(xiàn)與內(nèi)存屏障,下面就總結(jié)一下整個流程,文中有非常詳細的介紹及圖文示例,需要的朋友可以參考下
    2021-06-06
  • spring boot devtools在Idea中實現(xiàn)熱部署方法

    spring boot devtools在Idea中實現(xiàn)熱部署方法

    這篇文章主要介紹了spring boot devtools在Idea中實現(xiàn)熱部署方法及注意要點,需要的朋友可以參考下
    2018-02-02
  • MyBatis-Plus高級擴展詳解

    MyBatis-Plus高級擴展詳解

    本文介紹了MyBatis-Plus中邏輯刪除和樂觀鎖的實現(xiàn)概念、方法和示例,邏輯刪除通過更改記錄狀態(tài)模擬刪除,而樂觀鎖通過版本號或時間戳確保并發(fā)操作的正確性
    2025-03-03
  • Springboot 在普通類型注入Service或mapper

    Springboot 在普通類型注入Service或mapper

    這篇文章主要介紹了Springboot 在普通類型注入Service或mapper,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-11-11

最新評論