对于mysql主从机制的读写分离,对于写操作写入主库,读取操作读取从库
一、安装依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.6</version>
</dependency>
二、配置文件配置数据源
spring:
datasource:
dynamic:
#默认数据源
primary: master
datasource:
master:
username: root
password: xxxxx
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/xx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
slave:
username: root
password: xxx
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/xx?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
三、在service,如果是读取操作的话,则需要加上注解@DS(“slave”)即可,可看如下示例
@Service
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements ITUserService {
//读取走从库
@Override
@DS("slave")
public List<TUser> getUserList(){
return baseMapper.selectList(null);
}
//写操作默认走主库
@Override
@Transactional
public String adUser(TUser user){
baseMapper.insert(user);
return "OK";
}
}