最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

引言

在現(xiàn)代微服務架構中,通常需要與多個數(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ù)庫和用于非結構化數(shù)據(jù)的 NoSQL 數(shù)據(jù)庫。Spring Boot 為配置和管理多個數(shù)據(jù)源提供了出色的支持,使其成為現(xiàn)代微服務架構的理想選擇。

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ù)庫的資料請關注腳本之家其它相關文章!

相關文章

  • nacos配置讀取實現(xiàn)過程

    nacos配置讀取實現(xiàn)過程

    本文介紹了在Spring Boot應用中如何指定和使用配置文件,創(chuàng)建配置類讀取Nacos配置,并通過接口返回給前端,同時使用@RefreshScope實現(xiàn)配置實時刷新
    2026-01-01
  • JAVA使用TreeMap對字符串進行排序

    JAVA使用TreeMap對字符串進行排序

    這篇文章主要介紹了JAVA使用TreeMap對字符串進行排序,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • Java?面向?qū)ο笸ㄟ^new揭開對象實例化

    Java?面向?qū)ο笸ㄟ^new揭開對象實例化

    各位鐵汁們大家好呀,我們上次博客講了,通過?Student?student1?=?new?Student();就可以實例化一個對象,這個對象就有Student類中的所以成員變量??墒?對象student1?和?類Student到底是怎樣建立聯(lián)系的,在內(nèi)存中到底發(fā)生了什么
    2022-04-04
  • 老生常談java中的fail-fast機制

    老生常談java中的fail-fast機制

    下面小編就為大家?guī)硪黄仙U刯ava中的fail-fast機制。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • Java中this和super關鍵字的使用詳解

    Java中this和super關鍵字的使用詳解

    super?代表父類的存儲空間標識(可以理解為父親的引用)。?this代表當前對象的引用(誰調(diào)用就代表誰)。本文將通過簡單的示例介紹二者的使用與區(qū)別,需要的可以了解一下
    2022-10-10
  • 原來Java接口多實現(xiàn)還可以這樣玩

    原來Java接口多實現(xiàn)還可以這樣玩

    JAVA中類不直接支持多繼承,因為會出現(xiàn)調(diào)用的不確定性,所以JAVA將多繼承機制進行改良,在JAVA中變成了多實現(xiàn),這篇文章主要給大家介紹了關于Java接口多實現(xiàn)的相關資料,需要的朋友可以參考下
    2021-09-09
  • SpringBoot中TypeExcludeFilter的作用及使用方式

    SpringBoot中TypeExcludeFilter的作用及使用方式

    在SpringBoot應用程序中,TypeExcludeFilter通過過濾特定類型的組件,使它們不被自動掃描和注冊為bean,這在排除不必要的組件或特定實現(xiàn)類時非常有用,通過創(chuàng)建自定義過濾器并注冊到spring.factories文件中,我們可以在應用啟動時生效
    2025-01-01
  • 詳解Spring AOP 實現(xiàn)“切面式”valid校驗

    詳解Spring AOP 實現(xiàn)“切面式”valid校驗

    本篇文章主要介紹了詳解Spring AOP 實現(xiàn)“切面式”valid校驗,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • Javase隨機數(shù)類、日期類、包裝類的基礎知識示例詳解

    Javase隨機數(shù)類、日期類、包裝類的基礎知識示例詳解

    我們在開發(fā)時,除了操作一些固定的數(shù)字之外,有時候還要操作一些不確定的隨機數(shù),這篇文章主要介紹了Javase隨機數(shù)類、日期類、包裝類的基礎知識,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-09-09
  • 解決eclipse啟動tomcat時不能加載web項目的問題

    解決eclipse啟動tomcat時不能加載web項目的問題

    這篇文章主要介紹了解決eclipse啟動tomcat時不能加載web項目的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06

最新評論

沧源| 兴城市| 云林县| 于都县| 乌审旗| 正宁县| 紫云| 石楼县| 尤溪县| 江门市| 沁源县| 建德市| 五河县| 丹阳市| 兖州市| 贵定县| 黔南| 惠水县| 三明市| 兴安盟| 思南县| 驻马店市| 政和县| 平顺县| 蒲城县| 玉树县| 繁昌县| 永和县| 通江县| 淳安县| 昭苏县| 云和县| 广安市| 德江县| 阳信县| 额敏县| 阿拉善左旗| 恭城| 邻水| 长宁区| 东乡县|