在Java项目中实现MySQL读写分离需要进行一系列配置和代码编写。以下是一般的实施步骤,以Spring框架为例:
- 添加依赖:
<!-- pom.xml -->
<dependencies>
<!-- MySQL 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version> <!-- 版本号可能会有更新 -->
</dependency>
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
- 配置数据源和事务:
// DataSourceConfig.java
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = "com.example.repository",
entityManagerFactoryRef = "entityManagerFactory",
transactionManagerRef = "transactionManager"
)
public class DataSourceConfig {
@Primary
@Bean(name = "masterDataSource")
@ConfigurationProperties(prefix = "spring.datasource.master")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "slaveDataSource")
@ConfigurationProperties(prefix = "spring.datasource.slave")
public DataSource dataSourceSlave() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("masterDataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.example.domain")
.persistenceUnit("master")
.build();
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
- 创建实体类和DAO:
// User.java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String email;
// Getters and setters...
}
// UserRepository.java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// 读操作
@Query(value = "SELECT * FROM user WHERE id = :id", nativeQuery = true)
User findUserById(@Param("id") Long id);
// 写操作
@Modifying
@Query(value = "INSERT INTO user (username, email) VALUES (:username, :email)", nativeQuery = true)
void saveUser(@Param("username") String username, @Param("email") String email);
}
- Service层使用DAO进行读写操作:
// UserService.java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Transactional(readOnly = true)
public User getUserById(Long id) {
// 读操作,使用从数据库
return userRepository.findUserById(id);
}
@Transactional
public void saveUser(String username, String email) {
// 写操作,使用主数据库
userRepository.saveUser(username, email);
}
}
在这个例子中,UserRepository
中的findUserById
方法使用从数据库进行读操作,而saveUser
方法使用主数据库进行写操作。
这样,通过配置数据源和事务管理,以及在DAO层实施读写分离策略,你就能在Java项目中成功实现MySQL读写分离。确保在实际项目中根据具体情况进行适当的调整和优化。