当前位置: 首页 > article >正文

spring boot定时器实现定时同步数据

文章目录

目录

文章目录

前言

一、依赖和目录结构

二、使用步骤

2.1 两个数据源的不同引用配置

2.2 对应的mapper

2.3 定时任务处理 

总结



前言


一、依赖和目录结构

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.3.12.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.3.12.RELEASE</version>
    </dependency>


    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.1</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.49</version>
    </dependency>

</dependencies>

配置文件

server:
  port: 8089

spring:
  datasource:
    remote :
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://192.168.31.2/student?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
      username: root
      password: 111
    local :
      driver-class-name: com.mysql.jdbc.Driver
      jdbc-url: jdbc:mysql://192.168.31.1/student?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
      username: root
      password: 111


mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志

 

二、使用步骤

2.1 两个数据源的不同引用配置

package com.config;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 *
 * @date :Created in 2023/12/2 19:51
 * @description:本地数据源
 * @modified By:
 * @version:
 */
@Configuration
@MapperScan(basePackages = "com.local.Mapper", sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MybatisLocalConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.local")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory1(@Qualifier("dataSource1") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 设置mapper.xml文件的位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:localmapper/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate1(@Qualifier("sqlSessionFactory1") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }



}
@Configuration
@MapperScan(basePackages = "com.remote.Mapper", sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MybatisRemoteConfig {

    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.remote")
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory2(@Qualifier("dataSource2") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        // 设置mapper.xml文件的位置
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper2/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2(@Qualifier("sqlSessionFactory2") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

2.2 对应的mapper

public interface CourseOneMapper extends BaseMapper<Course> {
}
public interface CourseTwoMapper extends BaseMapper<Course> {


    /**
     * 批量插入
     * @param list
     */
    @Insert("<script> " +
            "INSERT INTO tbl_course (name, teacher) VALUES " +
            "<foreach collection='list' item='item' separator=','> " +
            "(#{item.name}, #{item.teacher})" +
            "</foreach> " +
            "</script>")
    void batchInsert(@Param("list") List<Course> list);
}

 

@TableName("tbl_course")
public class Course {


    @TableId(type = IdType.AUTO)
    private Integer id;
    private String name;
    private String teacher;


    public Course() {
    }

    public Course(Integer id, String name, String teacher) {
        this.id = id;
        this.name = name;
        this.teacher = teacher;
    }

    /**
     * 获取
     * @return id
     */
    public Integer getId() {
        return id;
    }

    /**
     * 设置
     * @param id
     */
    public void setId(Integer id) {
        this.id = id;
    }

    /**
     * 获取
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * 设置
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取
     * @return teacher
     */
    public String getTeacher() {
        return teacher;
    }

    /**
     * 设置
     * @param teacher
     */
    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

  @Override
    public String toString() {
        return "Course{id = " + id + ", name = " + name + ", teacher = " + teacher + "}";
    }
}

2.3 定时任务处理 

@EnableScheduling //开启定时
@Component
public class MySchedule {


    @Resource
    private CourseOneMapper courseOneMapper;

    @Resource
    private CourseTwoMapper courseTwoMapper;



    /**
     * 每隔10秒执行一次
     */
    @Scheduled(fixedDelay = 1000000)
    public void test(){

        //查询到要同步的数据
        List<Course> coursesOne = courseOneMapper.selectList(null);

        //批量插入
        courseTwoMapper.batchInsert(coursesOne);


    }



}

 

 


总结


http://www.kler.cn/a/154484.html

相关文章:

  • 某某科技笔试题
  • 【软件测试】设计测试用例的万能公式
  • Ubuntu VNC Session启动chromium和firefox报错
  • 用 Python 从零开始创建神经网络(五):损失函数(Loss Functions)计算网络误差
  • torchvision库在进行图片转换操作中报antialias参数没有显式设置会导致不同图片后端中的值不统一的警告信息
  • PaoluGPT——千里挑一
  • 深入理解Java中继承的高级使用方案
  • 不可抗力因素包括什么内容
  • 编译ubuntu kernel
  • 软件工程 - 第8章 面向对象建模 - 4 - 物理体系结构建模
  • 【Android知识笔记】性能优化专题(五)
  • php 中生成订单号
  • Adobe Bridge——牵线搭桥
  • 【ArcGIS Pro微课1000例】0040:ArcGIS Pro创建北极点、南极点
  • pandas基础操作2
  • Jmeter分布式压测
  • 基于PAM自定义ssh登陆认证
  • Linux expect命令详解
  • js-md5的简单使用
  • 深入理解贝叶斯分类与朴素贝叶斯模型(Naive Bayes, NB):从基础到实战
  • vscode插件问题
  • 基于SSM的网上书城
  • JOSEF约瑟时间继电器ARTD-DC110V-2H2D 0.25-2.5s导轨安装
  • 指针概念及应用
  • excel表格在线编辑(开源版)
  • 20231202_python练习_b站视频爬取(selenium浏览器模拟登录版)