Mysql主从+springboot+mybatis实践篇

简介: Mysql主从+springboot+mybatis实践篇

Mysql主从+springboot+mybatis实践篇

注意: 代码连接在文章末尾。

本次主要是按照上一个主从配置过后的数据库进行和springboot的连接实践操作。

环境配置

环境配置过程分为三个步骤

  1. 相关依赖引入
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--数据库三剑客-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.6</version>
        </dependency>
        <!-- google java lib -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>17.0</version>
        </dependency>
    </dependencies>
  1. application.yml配置文件配置。
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 你的主数据库密码
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://主数据库IP地址:端口/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
  db:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: 你的从数据库密码
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://从数据库ip地址:端口/test?useUnicode=true&characterEncoding=utf8&characterSetResults=utf8
mybatis:
  mapper-locations: classpath:mappers/*.xml
logging:
  level:
    com:
      example: debug

数据库相关配置文件编写

配置数据源

@Configuration
public class DruidConfig {
    /**
     * 主据源
     *
     * @return 返回数据源对象
     */
    @Primary
    @Bean(name = "writeDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }
    /**
     * 从数据源
     *
     * @return 返回数据源对象
     */
    @Bean(name = "readDataSource")
    @ConfigurationProperties(prefix = "spring.db")
    public DataSource readDataSource0() {
        return DataSourceBuilder.create().type(com.alibaba.druid.pool.DruidDataSource.class).build();
    }
}

配置数据源路由和事务等

@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan(basePackages = {"com.example.demoms.mapper"})
public class MybatisConfig
        implements TransactionManagementConfigurer, ApplicationContextAware {
    private static ApplicationContext context;
    /**
     * 数据源路由代理
     * 将数据源以map的形式放入数据源路由中,key分别为write和read,
     * 切面拦截指定方法的调用,判断是读还是写,将read或write放入ThreadLocale变量中
     * RoutingDataSource重写的determineCurrentLookupKey决定要使用哪个数据源,
     * 然后AbstractRoutingDataSource中的determineTargetDataSource的方法在map变量中将数据源取出,
     *
     * @return
     */
    @Bean
    public AbstractRoutingDataSource routingDataSourceProxy() {
        RoutingDataSource proxy = new RoutingDataSource();
        Map<Object, Object> targetDataSources = Maps.newHashMap();
        targetDataSources.put("write", context.getBean("writeDataSource", DataSource.class));
        targetDataSources.put("read", context.getBean("readDataSource", DataSource.class));
        proxy.setDefaultTargetDataSource(context.getBean("writeDataSource", DataSource.class));
        proxy.setTargetDataSources(targetDataSources);
        return proxy;
    }
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactoryBean sqlSessionFactory() throws IOException {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(routingDataSourceProxy());
        bean.setVfs(SpringBootVFS.class);
        bean.setTypeAliasesPackage("com.example.demoms.entity");
//        Resource configResource = new ClassPathResource("mybatis/mybatis.cfg.xml");
//        bean.setConfigLocation(configResource);
        ResourcePatternResolver mapperResource = new PathMatchingResourcePatternResolver();
        Resource[] resources = mapperResource.getResources("classpath:mappers/*.xml");
        bean.setMapperLocations(resources);
        return bean;
    }
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(routingDataSourceProxy());
    }
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (context == null) {
            context = applicationContext;
        }
    }
}

数据源路由类

public class RoutingDataSource extends AbstractRoutingDataSource {
    @Override
    protected Object determineCurrentLookupKey() {
        String typeKey = DataSourceContextHolder.getJdbcType();
        if (typeKey == null) {
            return "write";
        }else {
            if(typeKey.equals("read")) return "read";
            return "write";
        }
    }
}

定义切换数据源的注解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DynamicDataSource {
    /**
     * 数据源key值
     *
     * @return
     */
    String value() default "write";
}

定义切面,拦截定义的注解,获取ThreadLocal中的值

@Aspect
@Component
@Order(1)
public class DynamicDataSourceAspect {
    @Pointcut("@annotation(DynamicDataSource)")
    public void annotationPointcut() {
    }
    /**
     * 切换数据源
     *
     * @param point 节点
     */
    @Before("annotationPointcut()")
    public void setDataSourceType(JoinPoint point) {
        MethodSignature methodSignature =  (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        DynamicDataSource annotation = method.getAnnotation(DynamicDataSource.class);
        String value = annotation.value();
        System.out.println("切面中::"+value);
        if ("write".equals(value)){
            DataSourceContextHolder.write();
        }else {
            DataSourceContextHolder.read();
        }
    }
    @After("annotationPointcut()")
    public void clear() {
        System.out.println("切面中::清除类型");
        DataSourceContextHolder.clearDbType();
    }
}

DataSourceContextHolder类

public class DataSourceContextHolder {
    private static Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);
    private final static ThreadLocal<String> local = new ThreadLocal<>();
    public static ThreadLocal<String> getLocal() {
        return local;
    }
    public static void read() {
        logger.debug("切换至[读]数据源");
        System.out.println("切换至[读]数据源");
        local.set("read");
    }
    public static void write() {
        logger.debug("切换至[写]数据源");
        System.out.println("切换至[写]数据源");
        local.set("write");
    }
    public static String getJdbcType() {
        return local.get();
    }
    /**
     * 清理链接类型
     */
    public static void clearDbType() {
        local.remove();
    }
}

注解的使用

在service层的方法上加入@DynamicDataSource("read"),根据RoutingDataSource中的定义,如果不加注解,使用的是主数据源。

注意:以上方式在加入@Transactional注解或@LcnTransaction注解后并不能实现切换数据源,

测试

先配置好对应的mapper controller service 等。 在service的实现类中定义方法

@Override
    @DynamicDataSource("write")  //这个代表的是从写数据源里边进行数据查询
    public String getInfo() {
        return testMapper.getInfo();
    }

结果如下:

网络异常,图片无法展示
|

整体项目姐构图:

网络异常,图片无法展示
|

代码链接:https://englishcode.lanzoul.com/iphJ0019fq7e

相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
相关文章
|
人工智能 运维 Java
SpringBoot+MySQL实现动态定时任务
这是一个基于Spring Boot的动态定时任务Demo,利用spring-context模块实现任务调度功能。服务启动时会扫描数据库中的任务表,将任务添加到调度器中,并通过固定频率运行的ScheduleUpdater任务动态更新任务状态和Cron表达式。核心功能包括任务的新增、删除与Cron调整,支持通过ScheduledFuture对象控制任务执行。项目依赖Spring Boot 2.2.10.RELEASE,使用MySQL存储任务信息,包含任务基类ITask及具体实现(如FooTask),便于用户扩展运维界面以增强灵活性。
565 10
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,日期时间格式化是前后端交互的常见痛点。本文详细解析了 **@DateTimeFormat** 和 **@JsonFormat** 两个注解的用法,分别用于将前端传入的字符串解析为 Java 时间对象,以及将时间对象序列化为指定格式返回给前端。通过完整示例代码,展示了从数据接收、业务处理到结果返回的全流程,并总结了解决时区问题和全局配置的最佳实践,助你高效处理日期时间需求。
2398 0
|
存储 Java 数据库
Spring Boot 注册登录系统:问题总结与优化实践
在Spring Boot开发中,注册登录模块常面临数据库设计、密码加密、权限配置及用户体验等问题。本文以便利店销售系统为例,详细解析四大类问题:数据库字段约束(如默认值缺失)、密码加密(明文存储风险)、Spring Security配置(路径权限不当)以及表单交互(数据丢失与提示不足)。通过优化数据库结构、引入BCrypt加密、完善安全配置和改进用户交互,提供了一套全面的解决方案,助力开发者构建更 robust 的系统。
653 0
|
Java 数据库连接 数据库
Spring boot 使用mybatis generator 自动生成代码插件
本文介绍了在Spring Boot项目中使用MyBatis Generator插件自动生成代码的详细步骤。首先创建一个新的Spring Boot项目,接着引入MyBatis Generator插件并配置`pom.xml`文件。然后删除默认的`application.properties`文件,创建`application.yml`进行相关配置,如设置Mapper路径和实体类包名。重点在于配置`generatorConfig.xml`文件,包括数据库驱动、连接信息、生成模型、映射文件及DAO的包名和位置。最后通过IDE配置运行插件生成代码,并在主类添加`@MapperScan`注解完成整合
1888 1
Spring boot 使用mybatis generator 自动生成代码插件
|
Java 关系型数据库 MySQL
SpringBoot 通过集成 Flink CDC 来实时追踪 MySql 数据变动
通过详细的步骤和示例代码,您可以在 SpringBoot 项目中成功集成 Flink CDC,并实时追踪 MySQL 数据库的变动。
3927 45
|
监控 Java 关系型数据库
Spring Boot整合MySQL主从集群同步延迟解决方案
本文针对电商系统在Spring Boot+MyBatis架构下的典型问题(如大促时订单状态延迟、库存超卖误判及用户信息更新延迟)提出解决方案。核心内容包括动态数据源路由(强制读主库)、大事务拆分优化以及延迟感知补偿机制,配合MySQL参数调优和监控集成,有效将主从延迟控制在1秒内。实际测试表明,在10万QPS场景下,订单查询延迟显著降低,超卖误判率下降98%。
697 5
|
JSON 前端开发 Java
深入理解 Spring Boot 中日期时间格式化:@DateTimeFormat 与 @JsonFormat 完整实践
在 Spring Boot 开发中,处理前后端日期交互是一个常见问题。本文通过 **@DateTimeFormat** 和 **@JsonFormat** 两个注解,详细讲解了如何解析前端传来的日期字符串以及以指定格式返回日期数据。文章从实际案例出发,结合代码演示两者的使用场景与注意事项,解决解析失败、时区偏差等问题,并提供全局配置与局部注解的实践经验。帮助开发者高效应对日期时间格式化需求,提升开发效率。
4568 2
|
前端开发 Java Nacos
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
本文介绍了如何使用Spring Cloud Alibaba 2023.0.0.0技术栈构建微服务网关,以应对微服务架构中流量治理与安全管控的复杂性。通过一个包含鉴权服务、文件服务和主服务的项目,详细讲解了网关的整合与功能开发。首先,通过统一路由配置,将所有请求集中到网关进行管理;其次,实现了限流防刷功能,防止恶意刷接口;最后,添加了登录鉴权机制,确保用户身份验证。整个过程结合Nacos注册中心,确保服务注册与配置管理的高效性。通过这些实践,帮助开发者更好地理解和应用微服务网关。
2826 0
🛡️Spring Boot 3 整合 Spring Cloud Gateway 工程实践
|
前端开发 Java 数据库连接
Java后端开发-使用springboot进行Mybatis连接数据库步骤
本文介绍了使用Java和IDEA进行数据库操作的详细步骤,涵盖从数据库准备到测试类编写及运行的全过程。主要内容包括: 1. **数据库准备**:创建数据库和表。 2. **查询数据库**:验证数据库是否可用。 3. **IDEA代码配置**:构建实体类并配置数据库连接。 4. **测试类编写**:编写并运行测试类以确保一切正常。
1073 2
|
XML Java 数据库连接
微服务——SpringBoot使用归纳——Spring Boot集成MyBatis——基于注解的整合
本文介绍了Spring Boot集成MyBatis的两种方式:基于XML和注解的形式。重点讲解了注解方式,包括@Select、@Insert、@Update、@Delete等常用注解的使用方法,以及多参数时@Param注解的应用。同时,针对字段映射不一致的问题,提供了@Results和@ResultMap的解决方案。文章还提到实际项目中常结合XML与注解的优点,灵活使用两者以提高开发效率,并附带课程源码供下载学习。
1345 0

推荐镜像

更多