springboot多数据源配置

ops/2024/9/24 9:18:19/

Spring Boot 支持多数据源配置,这在需要同时操作多个数据库或者需要将读写分离的应用场景中非常有用。下面我将详细介绍如何在 Spring Boot 应用程序中配置和使用多数据源。

基础概念

  • 数据源: 数据源是用于连接数据库的对象,Spring Boot 默认使用 HikariCP 作为数据源。
  • JDBC: Java Database Connectivity,用于与数据库交互的标准接口。
  • JPA/Hibernate: 用于 ORM 操作的对象关系映射框架。

添加依赖

首先,你需要在 pom.xml 文件中添加相应的依赖。这里我们假设使用 MySQL 数据库,所以需要添加 HikariCP 和 MySQL JDBC 驱动。

<dependencies><!-- Spring Boot Starter Data JPA --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><!-- HikariCP 数据源 --><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId></dependency><!-- MySQL JDBC 驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency>
</dependencies>

配置多数据源

application.propertiesapplication.yml 文件中配置两个数据源,比如 primarysecondary

application.properties 示例:
# 主数据源
spring.datasource.primary.url=jdbc:mysql://localhost:3306/primary_db?useUnicode=true&characterEncoding=utf8
spring.datasource.primary.username=root
spring.datasource.primary.password=secret
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.primary.hikari.maximum-pool-size=10# 从数据源
spring.datasource.secondary.url=jdbc:mysql://localhost:3306/secondary_db?useUnicode=true&characterEncoding=utf8
spring.datasource.secondary.username=root
spring.datasource.secondary.password=secret
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.hikari.maximum-pool-size=5# JPA 配置
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
application.yml 示例:
spring:datasource:primary:url: jdbc:mysql://localhost:3306/primary_db?useUnicode=true&characterEncoding=utf8username: rootpassword: secretdriver-class-name: com.mysql.cj.jdbc.Driverhikari:maximum-pool-size: 10secondary:url: jdbc:mysql://localhost:3306/secondary_db?useUnicode=true&characterEncoding=utf8username: rootpassword: secretdriver-class-name: com.mysql.cj.jdbc.Driverhikari:maximum-pool-size: 5jpa:show-sql: truehibernate:ddl-auto: update

配置 DataSource Bean

在 Spring Boot 中,你可以通过 @Configuration 类来定义 DataSource Bean。下面是一个例子:

java">@Configuration
public class DataSourceConfig {@Bean(name = "primaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.primary")public DataSource primaryDataSource() {return DataSourceBuilder.create().build();}@Bean(name = "secondaryDataSource")@ConfigurationProperties(prefix = "spring.datasource.secondary")public DataSource secondaryDataSource() {return DataSourceBuilder.create().build();}
}

创建 Repository 和 Service

为了使用不同的数据源,你需要为每个数据源创建一个实体类、Repository 和 Service。

实体类 (Entity)
java">@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;// Getters and Setters
}
Repository (使用不同的数据源)
java">@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}@Repository(lookup = "secondaryUserRepository")
public interface SecondaryUserRepository extends JpaRepository<User, Long> {
}
Service
java">@Service
public class UserService {private final UserRepository userRepository;private final SecondaryUserRepository secondaryUserRepository;public UserService(UserRepository userRepository, @Qualifier("secondaryUserRepository") SecondaryUserRepository secondaryUserRepository) {this.userRepository = userRepository;this.secondaryUserRepository = secondaryUserRepository;}public List<User> findAllPrimaryUsers() {return userRepository.findAll();}public List<User> findAllSecondaryUsers() {return secondaryUserRepository.findAll();}
}

这样就完成了基本的多数据源配置。你可以根据实际需求调整数据源的数量和配置细节。如果你需要在同一个实体上切换数据源,可能还需要配置不同的实体管理器工厂 (EntityManagerFactory) 和实体管理器 (EntityManager)。如果你需要进一步的帮助,请告诉我你具体的使用场景,我可以给出更详细的指导。


http://www.ppmy.cn/ops/93436.html

相关文章

猫咪掉毛清洁不用愁,希喂、352宠物空气净化器大PK,数据揭秘!

随着养宠人群的增多&#xff0c;市场关注到铲屎官们的需要&#xff0c;带来了新的科技产品——宠物空气净化器。宠物空气净化器是在普通空气净化器基础上&#xff0c;调整服务对象&#xff0c;为吸附宠物毛发而设计的。不少消费者被它的功能所吸引&#xff0c;打算购入使用。然…

Spring Boot读取配置的几种方式

文章目录 Value 注解读取配置ConfigurationProperties 绑定配置Environment 对象读取配置PropertySource 注解读取外部配置文件ApplicationArguments 读取命令行参数Bean 方法和 ConfigurationProperties 结合 在 Spring Boot 中&#xff0c;可以通过多种方式读取配置。Spring …

Android系统安全 — 6.5 Bluetooth安全连接原理

1 蓝牙协议架构和简称 蓝牙协议栈主要分&#xff1a;APPS层&#xff08;应用层&#xff0c;包括音频播放器&#xff0c;蓝牙遥控&#xff0c;智能家居APP等&#xff09;&#xff0c; HOST层&#xff08;中间层协议&#xff0c;包括GAP,SMP,ATT/GATT, L2CAP, AMP Manager&#x…

如何在 Vue.js 项目中动态设置页面标题

目录 方法 1:使用 Vue Router 的元信息(meta) 步骤 1: 配置路由元信息 步骤 2: 使用路由守卫设置标题 方法 2:在组件内设置标题 在组件挂载时设置标题 使用响应式数据动态更新标题 在开发 Vue.js 应用时,设置动态页面标题是常见需求,尤其当应用包含多个页面时,为每…

Stable Diffusion绘画 | 进阶语法

控制提示词生效时间 使用格式1&#xff1a;[提示词:0-1数值] 举例&#xff1a;forest,lots of trees and stones,[flowers:0.7] 其中 [flowers:0.7] 表示整体画面采样值达到70%的进程以后&#xff0c;才开始计算花的采样。 因此&#xff0c;花的数量仅仅只跑了末段的30%&am…

使用js和css 实现div旋转围绕圆分布排列

记录&#xff0c;以防忘记 围绕圆 import React, { useEffect } from react; import ./index.scoped.scss;const Test () > {const arr Array.from({ length: 28 }, (_, index) > index 1);useEffect(() > {const dayTotal arr.length;// 动态设置每个点的旋转角…

idea过滤器 过滤所有页面除了登录页面 !(包括白名单简洁概括)

1、创建过滤器包&#xff0c;创建LoginFilter类 2.在LoginFilter类中写过滤代码 //白名单List<String> whitelist Arrays.asList("/login.jsp");//用来存放配置文件中Action节点的属性List<Action> actionList new ArrayList<>(); public void …

js深度解构

深度解构&#xff08;Deep Destructuring&#xff09;是指在解构赋值中&#xff0c;解构对象或数组中的嵌套结构。它允许你从复杂的数据结构中直接提取所需的嵌套数据&#xff0c;使代码更加简洁明了。 对象&#xff1a; const person {name: John,address: {city: New York…