下面我将为你详细讲解“详解springboot实现多数据源代码实战”的完整攻略。
什么是多数据源
多数据源即在一个应用中使用多个数据源,通常在企业级应用程序中使用,因为这些程序通常需要访问多个不同的数据库。使用多个数据源允许应用程序同时连接到不同的数据源,以提高性能并减少响应时间。
SpringBoot实现多数据源
SpringBoot 非常适合于创建微服务,它也为我们提供了方便的方式来实现多数据源。让我们看一下通过 Spring Boot 实现多数据源的示例。
添加数据库依赖
首先,我们先添加 Spring Boot JPA 和 MySQL Connector/J 这两个依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
配置数据源
在 application.yml
文件中配置数据源相关信息,例如:
spring:
datasource:
primary:
url: jdbc:mysql://localhost:3306/database1
username: user1
password: password1
secondary:
url: jdbc:mysql://localhost:3306/database2
username: user2
password: password2
在上面的例子中,我们定义了两个数据源:primary 和 secondary。它们分别连接到两个不同的 MySQL 数据库。
创建实体类和 repository
假设我们有两张表:users
和 customers
,分别在不同的数据库中,我们需要创建对应的实体类和 repository。
首先是 users
表在 primary
数据库中的相关代码:
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
接着是 customers
表在 secondary
数据库中的相关代码:
@Entity
@Table(name = "customers")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
配置多数据源
为了在应用程序中使用多个数据源,我们需要为它们分别配置数据源和事务管理器。我们可以通过创建多个配置对象来完成这个任务。
首先是 primary
数据源的配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager",
basePackages = { "com.example.demo.primary.repository" }
)
public class PrimaryDatabaseConfig {
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.example.demo.primary.entity")
.persistenceUnit("primary")
.build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
接着是 secondary
数据源的配置:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "secondaryEntityManagerFactory",
transactionManagerRef = "secondaryTransactionManager",
basePackages = { "com.example.demo.secondary.repository" }
)
public class SecondaryDatabaseConfig {
@Bean(name = "secondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondaryEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean
entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("secondaryDataSource") DataSource dataSource
) {
return builder
.dataSource(dataSource)
.packages("com.example.demo.secondary.entity")
.persistenceUnit("secondary")
.build();
}
@Bean(name = "secondaryTransactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("secondaryEntityManagerFactory") EntityManagerFactory entityManagerFactory
) {
return new JpaTransactionManager(entityManagerFactory);
}
}
使用多数据源
现在我们已经完成了多个数据源的配置,接下来就可以在代码中使用它们。
首先是使用 primary
数据源操作 users
表:
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
// ...
}
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/")
public List<User> getUsers() {
return userService.getUsers();
}
// ...
}
再来是使用 secondary
数据源操作 customers
表:
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
// ...
}
@RestController
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/")
public List<Customer> getCustomers() {
return customerService.getCustomers();
}
// ...
}
到这里,我们已经完成了 Spring Boot 实现多数据源的攻略,你现在已经知道如何配置和使用多个数据源。如果你需要在你的应用程序中使用多个数据库,请使用上述方法。
示例代码
下面是使用多数据源的两个示例代码:
示例1:使用 primary
数据源操作 users
表
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getUsers() {
return userRepository.findAll();
}
public void addUser(User user) {
userRepository.save(user);
}
}
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@GetMapping("/")
public List<User> getUsers() {
return userService.getUsers();
}
@PostMapping("/")
public void addUser(@RequestBody User user) {
userService.addUser(user);
}
}
示例2:使用 secondary
数据源操作 customers
表
@Service
public class CustomerService {
private final CustomerRepository customerRepository;
@Autowired
public CustomerService(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public List<Customer> getCustomers() {
return customerRepository.findAll();
}
public void addCustomer(Customer customer) {
customerRepository.save(customer);
}
}
@RestController
@RequestMapping("/customers")
public class CustomerController {
private final CustomerService customerService;
@Autowired
public CustomerController(CustomerService customerService) {
this.customerService = customerService;
}
@GetMapping("/")
public List<Customer> getCustomers() {
return customerService.getCustomers();
}
@PostMapping("/")
public void addCustomer(@RequestBody Customer customer) {
customerService.addCustomer(customer);
}
}
希望这些示例代码可以帮助你更好地理解多数据源的实现。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:详解spring boot实现多数据源代码实战 - Python技术站