SpringBoot通过JPA连接Mysql集群
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 为什么要进行Mysql的主从复制
- 一、Mysql主从复制配置
- 1.配置主数据库
- 2.配置从数据库
- 3.在主数据库上进行用户授权
- 4.在从数据库上进行连接
- 二、SpringBoot通过JPA的方式连接使用Mysql集群
- 1.配置文件
- 2.数据源对象创建
- 3.数据源路由配置
- 4.数据源对象缓存
- 5.多数据源配置
- 6.配置AOP
- 7.在Service中的使用
- 8.代码目录结构
为什么要进行Mysql的主从复制
1.可以实现数据库的读写分离,提高对数据的访问效率
2.可以对数据库进行备份
一、Mysql主从复制配置
本文使用了一主一从的集群模式,对mysql数据库进行主从复制配置。
本文对于数据库的安装过程不再过多赘述,直接从数据库的配置写起。
1.配置主数据库
(1)首先进入到主数据库的配置文件中
vi /etc/my.cnf #进入到主MySQL的配置文件中
(2)添加配置
[mysqld]
skip-name-resolve#禁用DNS解析,避免网络DNS解析服务引发访问Mysql的错误server_id=1 #配置集群中的id 此id一定要唯一
log-bin=mysql-bin#在对主mysql服务器进行操作时,生成的二进制日志,从服务器主要通过该日志进行数据的同步
read-only=0#可以对该数据库进行读写操作
binlog-do-db=db1#进行主从复制所用到的数据库#主从复制忽略的数据库
replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
(3)重启主数据库
systemctl restart mysqld
2.配置从数据库
对从数据库配置文件添加配置
[mysqld]
skip-name-resolveserver_id=2
log-bin=mysql-bin
read-only=1#配置成只读模式
binlog-do-db=db1replicate-ignore-db=mysql
replicate-ignore-db=sys
replicate-ignore-db=information_schema
replicate-ignore-db=performance_schema
然后重启从数据库
3.在主数据库上进行用户授权
进行用户授权
grant replication slave on *.* to 'rep'@'%' identified by '12345';#用户名rep和密码12345可以根据自己的需求来起
查看主数据库状态
show master status
4.在从数据库上进行连接
进行主数据库连接
change master to master_host='172.168.4.18',
master_user='rep',master_password='12345',
master_log_file='mysql-bin.000006',master_log_pos=15353,master_port=3306
启动从数据库
start slave
查看从数据库状态
show slave status
在从数据库中的状态中,如果Slave_IO_Running和Slave_SQL_Running同时为Yes,则证明主从复制集群配置成功。
二、SpringBoot通过JPA的方式连接使用Mysql集群
1.配置文件
application.yml
spring:datasource: #多数据源配置master:jdbc-url: jdbc:mysql://ip:port/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=falseusername: rootpassword: 12345driverClassName: com.mysql.cj.jdbc.Driverslave:jdbc-url: jdbc:mysql://ip:port/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=falseusername: rootpassword: 12345driverClassName: com.mysql.cj.jdbc.Driverjpa:show-sql: truehibernate:naming:physical-strategy: org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy
2.数据源对象创建
@Slf4j
@Configuration
public class DataSourceConfiguration {@Primary@Bean@ConfigurationProperties(prefix = "spring.datasource.master")public DataSource masterDataSource() {log.info("create master datasource...");return DataSourceBuilder.create().build();}@Bean@ConfigurationProperties(prefix = "spring.datasource.slave")public DataSource slaveDataSource() {log.info("create slave datasource...");return DataSourceBuilder.create().build();}}
3.数据源路由配置
@Slf4j
public class DynamicDataSourceRouter extends AbstractRoutingDataSource {/**** 决定使用哪个数据源*/@Overrideprotected Object determineCurrentLookupKey() {return DataSourceContextHolder.getDataSource();}
}
4.数据源对象缓存
@Slf4j
public class DataSourceContextHolder {private static final ThreadLocal<String> holder = new ThreadLocal<>();public static void setDataSource(String type) {holder.set(type);}public static String getDataSource() {String lookUpKey = holder.get();return lookUpKey == null ? "masterDataSource" : lookUpKey;}public static void clear() {holder.remove();}
}
5.多数据源配置
主要是配置EntityManagerFactory和PlatformTransactionManager
@Slf4j
@Configuration
@EnableJpaRepositories(value = "com.imooc.dao.repository", entityManagerFactoryRef = "entityManagerFactoryBean", transactionManagerRef = "transactionManagerBean")
public class JpaEntityManager {@Autowiredprivate JpaProperties jpaProperties;@Autowiredprivate HibernateProperties hibernateProperties;@Resource(name = "masterDataSource")private DataSource masterDataSource;@Resource(name = "slaveDataSource")private DataSource slaveDataSource;@Bean(name = "routingDataSource")public AbstractRoutingDataSource routingDataSource() {DynamicDataSourceRouter proxy = new DynamicDataSourceRouter();Map<Object, Object> targetDataSources = new HashMap<>(2);targetDataSources.put("masterDataSource", masterDataSource);targetDataSources.put("slaveDataSource", slaveDataSource);//需要将可能用到的数据源存储到targetDataSources//后续通过determineCurrentLookupKey()方法匹配出所需要的数据源proxy.setDefaultTargetDataSource(masterDataSource);proxy.setTargetDataSources(targetDataSources);return proxy;}@Bean(name = "entityManagerFactoryBean")public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {Map<String, String> properties = getVendorProperties();return builder.dataSource(routingDataSource())//注入routingDataSource.properties(properties)//注入属性 application.yml中的.packages("com.imooc.entity").persistenceUnit("myPersistenceUnit") //因为只构建一个EntityManagerFactory可以忽略该属性.build();}@Primary@Bean(name = "transactionManagerBean")public PlatformTransactionManager transactionManagerBean(EntityManagerFactoryBuilder builder) {return new JpaTransactionManager(entityManagerFactoryBean(builder).getObject());}private Map getVendorProperties() {return hibernateProperties.determineHibernateProperties(jpaProperties.getProperties(), new HibernateSettings());}
}
6.配置AOP
@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {@Pointcut("execution(* com.imooc.service..*.*(..))")private void aspect() {}@Around("aspect()")public Object around(ProceedingJoinPoint joinPoint) throws Throwable {String method = joinPoint.getSignature().getName();//获取方法名字if (method.startsWith("find") || method.startsWith("select") || method.startsWith("query") || method.startsWith("search")) {DataSourceContextHolder.setDataSource("slaveDataSource");log.info("switch to slave datasource...");} else {DataSourceContextHolder.setDataSource("masterDataSource");log.info("switch to master datasource...");}try {return joinPoint.proceed();}finally {log.info("清除 datasource router...");DataSourceContextHolder.clear();}}}
7.在Service中的使用
@Service
public class UserService {@Autowiredprivate UserRepository userRepository;public User addOne(User user) {return userRepository.save(user);}public User findById(Long userId) {if(userRepository.findById(userId).isPresent())return userRepository.findById(userId).get();elsereturn null;}public List<User> findUsers(){return userRepository.getUser();}}
8.代码目录结构
SpringBoot通过JPA连接Mysql集群相关推荐
- go连接mysql集群_Mysql集群方案-Go语言中文社区
MySql集群原理 比如有三台mysql,当java使用数据源连接池进行连接的时候,应该连接哪台呢?其实连接哪台都不行,万一你连接的mysql,突然宕机了,那么数据都查询不到了,其实应该连接mycat ...
- go连接mysql集群_什么是MySQL集群-Go语言中文社区
一.什么是MySQL集群 MySQL集群是一个无共享的(shared-nothing).分布式节点架构的存储方案,其目的是提供容错性和高性能. 数据更新使用读已提交隔离级别(read-committe ...
- spring jpa mysql集群_Spring Boot系列之十四 JPA 连接mycat
接 本文介绍使用spring-data-jpa连接mycat实现应用的读写分离. 系统环境spring-boot 1.4.3-RELEASE jdk1.8 进入正题application.yml配置文 ...
- springboot连接redis集群
开启redis服务和客户端 查看下当前redis的进程 [root@localhost ~]# ps -ef | grep redis 启动redis服务 [root@localhost ~]# cd ...
- mysql 集群 qps_MySQL Cluster:如何通过扩展为MySQL带来2亿QPS
本篇文章的目的在于介绍MySQL Cluster--也就是MySQL的一套内存内.实时.可扩展且具备高可用性的版本.在解决标题中所提到的每秒2亿查询处理能力问题之前,我们先对MySQL集群的背景信息及 ...
- mysql集群-ndb
Mysql cluster介绍: MySQL Cluster 是一种技术,该技术允许在无共享的系统中部署"内存中"数据库的 Cluster .通过无共享体系结构,系统能够使用廉价的 ...
- Docker中搭建redis分片集群,搭建redis哨兵结构,实现springboot中对redis分片集群、哨兵结构的访问,Redis缓存雪崩、缓存击穿处理(非关系型数据库技术课程 第十二周)
文章目录 一.要求: 二.知识总结 缓存雪崩 解决方案 docker中redis分片集群搭建 配置好配置文件 redis-6380.conf redis-6381.conf redis-6382.co ...
- mysql集群安装(centos)
永不放弃,一切皆有可能!!! 只为成功找方法,不为失败找借口! mysql集群安装(centos) mysql cluster : 1. 基于NDB Cluster 的分布式数据库系统 2. mysq ...
- mysql 集群实践_MySQL Cluster集群探索与实践
MySQL集群是一种在无共享架构(SNA,Share Nothing Architecture)系统里应用内存数据库集群的技术.这种无共享的架构可以使得系统使用低廉的硬件获取高的可扩展性. MySQL ...
最新文章
- Vue.js 学习路线
- 利用PySpark进行迁移学习的多类图像分类
- .NET Core开发实战(第26课:工程结构概览:定义应用分层及依赖关系)--学习笔记...
- android软件百分比怎么实现,Android自实现百分比布局
- html中如何计算图片的像素,html – 浏览器的1px计算问题(子像素问题)
- Python入门-行和缩进
- headfirst设计模式(2)—观察者模式
- 使用Frigga实现WEB方式对服务的监控
- 负载均衡算法 : 加权轮询
- python-day1-用户的输入输出
- Cannot load supported formats: Cannot run program svn: CreateProcess error=2, μ
- 基于java的校园兼职管理系统_基于JAVA WEB的大学生兼职管理系统的分析与设计
- python百度网盘-百度网盘 Python 客户端
- CentOS7安装杀毒软件ClamAV图形界面ClamTk
- 豆瓣读书数据分析实战
- 强烈推荐代码生成器Cursor
- NANK南卡无线蓝牙耳机体验:身材虽大,续航却格外长
- 虚拟机的迁移和复制分发
- NLP Python
- linux查询某域线程是否满了,Linux多线程编程的时候怎么查看一个进程中的某个线程是否存活...
热门文章
- 本地vue-router模式设置为mode:‘history‘时,页面空白,无法加载
- 和数区块链技术投身Web3.0脚踏实地变革中蕴含机遇
- Python入门(7)——分支语句与循环语句
- 建军节献礼!J20航模遥控器开源项目系列教程(一)制作教程 | 基础版V1.0发布,从0到1
- MySQL调试--explain命令详解
- 车迷福利|高清超级跑车手机壁纸
- 学生类java程序_java 创建学生类
- hdu 4389 囧,打表
- 设计模式:(迭代器模式)
- c语言头文件命名规则,C语言头文件规则.doc