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

spring.main.web-application-type=none
在定时任务配置文件中 禁用内部tomcat并且能正常使用web里面的注解 并且不需要端口就能启动定时任务


前言


一、依赖和目录结构

a29536f313ba44f1bf57792481344295.jpeg

<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);


    }



}


总结

在Java中,@Scheduled注解是用于指定定时任务的执行规则的。它可以应用于方法或者类上面。

如果应用于方法上,该方法将被视为一个定时任务,并按照指定的时间规则进行调度执行。

如果应用于类上,该类中所有带有@Scheduled注解的方法都会被视为定时任务。

@Scheduled注解的参数可以用来指定任务的执行规则,包括以下几个方面:

fixedDelay:指定任务开始执行之后的延迟时间(毫秒数),任务执行完成后,再经过指定的延迟时间再次执行。例如:@Scheduled(fixedDelay = 5000)表示任务开始执行后,等待5秒后再次执行。

fixedRate:指定任务开始执行之后的间隔时间(毫秒数),任务执行完成后,立即开始下一次执行。例如:@Scheduled(fixedRate = 5000)表示任务开始执行后,每隔5秒执行一次。

initialDelay:指定任务首次执行的延迟时间(毫秒数)。例如:@Scheduled(initialDelay = 5000)表示任务首次执行延迟5秒。

cron:使用Cron表达式指定复杂的任务执行规则。Cron表达式由6个部分组成,分别表示秒、分钟、小时、日期、月份和星期几。例如:@Scheduled(cron = "0 0 12 * * ?")表示每天中午12点执行任务。

除了以上参数,@Scheduled注解还支持fixedDelayString、fixedRateString和zone等属性,可以使用字符串形式的时间间隔和指定时区。

需要注意的是,@Scheduled注解需要与@EnableScheduling注解一起使用,以启用定时任务的功能。

  • 15
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 spring boot 定时器库存预警的代码示例: 首先,在 pom.xml 中添加依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> ``` 然后,在 application.properties 中配置邮件发送相关的属性: ``` spring.mail.host=smtp.example.com spring.mail.port=587 spring.mail.username=yourusername spring.mail.password=yourpassword spring.mail.properties.mail.smtp.auth=true spring.mail.properties.mail.smtp.starttls.enable=true spring.mail.properties.mail.smtp.starttls.required=true ``` 接下来,创建一个定时器类 InventoryWarningTask,并添加 @Component 注解,表示这是一个组件类: ```java @Component public class InventoryWarningTask { @Autowired private ProductService productService; @Autowired private JavaMailSender javaMailSender; @Scheduled(cron = "${inventory.warning.cron}") public void execute() { List<Product> products = productService.getProducts(); for (Product product : products) { if (product.getInventory() < product.getWarningInventory()) { String subject = "库存预警:" + product.getName(); String text = "商品名称:" + product.getName() + "\n" + "当前库存:" + product.getInventory() + "\n" + "警戒库存:" + product.getWarningInventory(); sendEmail(subject, text); } } } private void sendEmail(String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom("[email protected]"); message.setTo("[email protected]"); message.setSubject(subject); message.setText(text); javaMailSender.send(message); } } ``` 在定时器类中,我们使用 @Autowired 注解将 ProductService 和 JavaMailSender 注入进来。在 execute() 方法中,我们获取所有商品,检查库存是否低于警戒库存。如果是,则发送邮件给管理员。 定时器的执行时间通过 @Scheduled 注解的 cron 属性指定,这里使用了 ${inventory.warning.cron} 属性占位符,需要在 application.properties 中定义该属性的值,例如: ``` inventory.warning.cron=0 0 12 * * ? ``` 表示每天中午 12 点执行一次。 以上就是一个简单的 spring boot 定时器库存预警的代码示例。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值