对于mysql主从机制的读写分离,对于写操作写入主库,读取操作读取从库
一、安装依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.6</version>
</dependency>
二、配置文件配置数据源文章来源:https://www.toymoban.com/news/detail-824756.html
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”)即可,可看如下示例文章来源地址https://www.toymoban.com/news/detail-824756.html
@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";
}
}
到了这里,关于spring boot+mybatis-plus配置读写分离的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!