Spring Boot应用中集成与使用多数据源

2024-08-30 06:52

本文主要是介绍Spring Boot应用中集成与使用多数据源,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Spring Boot应用中集成与使用多数据源

1. 前言

通过定义和使用多个数据源,能在Spring Boot应用中实现更复杂的数据管理场景,比如读写分离、数据冗余等。

2. 准备工作
  • 环境准备:确保已经准备好Spring Boot的开发环境。
  • 数据库准备:在本地或云服务上创建两个数据库,如下文所示。

3. 创建Spring Boot项目
  1. 使用Spring Initializr创建项目:https://start.spring.io/。
  2. pom.xml中添加必要的依赖,包括JPA、Spring Boot Parent、数据库驱动等。

4. 配置多数据源

application.ymlapplication.properties中配置:

# application.yml
spring:datasource:primary:url: jdbc:mysql://localhost:3306/db1username: userpassword: passworddriver-class-name: com.mysql.jdbc.Driverhikari:connection-timeout: 30000maximum-pool-size: 20secondary:url: jdbc:mysql://localhost:3306/db2username: userpassword: passworddriver-class-name: com.mysql.jdbc.Driverhikari:connection-timeout: 30000maximum-pool-size: 20

5. 创建实体类及Repository

Entity Class - User (For Primary Database):

package com.example.multidatasource.entity;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name = "users")
public class User {@Idprivate Long id;private String name;private String email;// getter, setter, constructors
}

Entity Class - Product (For Secondary Database):

package com.example.multidatasource.entity;import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;@Entity
@Table(name = "products")
public class Product {@Idprivate Long id;private String name;private int price;// getter, setter, constructors
}

Repository (Primary):

package com.example.multidatasource.repository;import com.example.multidatasource.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

Repository (Secondary):

package com.example.multidatasource.repository;import com.example.multidatasource.entity.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}
6. 服务层配置与使用多数据源
package com.example.multidatasource.service;import com.example.multidatasource.entity.Product;
import com.example.multidatasource.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;@Service
public class ProductService {private final ProductRepository productRepository;@Autowiredpublic ProductService(ProductRepository productRepository) {this.productRepository = productRepository;}public Product createProduct(String name, int price) {Product product = new Product();product.setName(name);product.setPrice(price);return productRepository.save(product);}
}

服务层同样应当遵循具体数据源的配置,确保通过合适的数据源进行持久化操作。

7. 事务与多数据源管理

针对跨数据源的事务操作,需要在@Service中配置@Transactional注解:

@Service
public class MultiDataSourceTransactionService {private final UserRepository userRepository;private final ProductRepository productRepository;@Autowiredpublic MultiDataSourceTransactionService(UserRepository userRepository, ProductRepository productRepository) {this.userRepository = userRepository;this.productRepository = productRepository;}// So that it's only using the primary dataSource@Transactional(propagation = Propagation.REQUIRED)public void performCreateUserAndProduct() {userRepository.save(new User("John Doe", "john@example.com"));productRepository.save(new Product("Widget", 1000));}
}

通过这种方式,可以确保同一个请求中的所有操作,要么全部成功,要么全部回滚。

8. 配置及测试

确保所有的Bean和配置类被正确注解,测试应用是否能够启动,数据源是否能够正确读写数据。

这篇关于Spring Boot应用中集成与使用多数据源的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1120103

相关文章

Debezium 与 Apache Kafka 的集成方式步骤详解

《Debezium与ApacheKafka的集成方式步骤详解》本文详细介绍了如何将Debezium与ApacheKafka集成,包括集成概述、步骤、注意事项等,通过KafkaConnect,D... 目录一、集成概述二、集成步骤1. 准备 Kafka 环境2. 配置 Kafka Connect3. 安装 D

Java中ArrayList和LinkedList有什么区别举例详解

《Java中ArrayList和LinkedList有什么区别举例详解》:本文主要介绍Java中ArrayList和LinkedList区别的相关资料,包括数据结构特性、核心操作性能、内存与GC影... 目录一、底层数据结构二、核心操作性能对比三、内存与 GC 影响四、扩容机制五、线程安全与并发方案六、工程

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程

如何使用Java实现请求deepseek

《如何使用Java实现请求deepseek》这篇文章主要为大家详细介绍了如何使用Java实现请求deepseek功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1.deepseek的api创建2.Java实现请求deepseek2.1 pom文件2.2 json转化文件2.2

Java调用DeepSeek API的最佳实践及详细代码示例

《Java调用DeepSeekAPI的最佳实践及详细代码示例》:本文主要介绍如何使用Java调用DeepSeekAPI,包括获取API密钥、添加HTTP客户端依赖、创建HTTP请求、处理响应、... 目录1. 获取API密钥2. 添加HTTP客户端依赖3. 创建HTTP请求4. 处理响应5. 错误处理6.

Spring AI集成DeepSeek的详细步骤

《SpringAI集成DeepSeek的详细步骤》DeepSeek作为一款卓越的国产AI模型,越来越多的公司考虑在自己的应用中集成,对于Java应用来说,我们可以借助SpringAI集成DeepSe... 目录DeepSeek 介绍Spring AI 是什么?1、环境准备2、构建项目2.1、pom依赖2.2

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

C++ Primer 多维数组的使用

《C++Primer多维数组的使用》本文主要介绍了多维数组在C++语言中的定义、初始化、下标引用以及使用范围for语句处理多维数组的方法,具有一定的参考价值,感兴趣的可以了解一下... 目录多维数组多维数组的初始化多维数组的下标引用使用范围for语句处理多维数组指针和多维数组多维数组严格来说,C++语言没

Spring Cloud LoadBalancer 负载均衡详解

《SpringCloudLoadBalancer负载均衡详解》本文介绍了如何在SpringCloud中使用SpringCloudLoadBalancer实现客户端负载均衡,并详细讲解了轮询策略和... 目录1. 在 idea 上运行多个服务2. 问题引入3. 负载均衡4. Spring Cloud Load

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录