SpringBoot 集成框架

Quartz 框架核心概念

Quartz 任务调度的主要组成元素有: Trigger(触发器)、 Scheduler(任务调度器)、 Job(任务)。 其中 Trigger,
Job 是元数据, Scheduler 才是任务调度的控制器。 具体的含义描述如下:
⚫ JobDetail: quartz 每次都会直接创建一个 JobDetail,同时创建一个 Job 实例,它不直接接受一个 Job
的实例,但是它接受一个 Job 的实现类,通过 new instance()的反射方式来实例一个 Job,在这里 Job
是一个接口,我们需要自己编写类去实现这个接口。
⚫ Trigger : 它由 SimpleTrigger 和 CronTrigger 组成, 当仅需要触发一次或者以固定间隔周期性触发执
行, SimpleTrigger是最适合的选择。而CronTrigger则可以定义Cron 表达式定义出各种复杂的调度
方案,如每天上午 9:00 执行,每周一、周三、周五下午 5:00 执行。
⚫ Scheduler:调度器, JobDetail 和 Trigger 可以通过 Scheduler 绑定到一起。

SpringBoot 集成 Quartz 框架

SpringBoot 集成 Quartz 框架的基本步骤

  1. 引入 Quartz 依赖
<!-- pom文件 Spring Quartz依赖 -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>2.2.1</version>
<exclusions>
<exclusion>
<artifactId>slf4j-api</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
  1. 我们需要使用注解@Configuration 来定义一个配置类,代码如下:
@Configuration //相当于xml文件中的<beans>
public class ConfigMyTools {
/**
* 格式化当前日期
* @return
*/
@Bean("dateFormat")
public SimpleDateFormat dateFormat(){
return new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
}
}
  1. 为了方便我们看清楚任务调度的次数,我们声明一个辅助类,代码如下:
@Component("myTask")
public class MyTask {
private int count = 0;
public void say(){
System.out.println("大家好,我是springboot任务调度=>"+count++);
}
}
  1. 接下创建一个任务调度的类,代码如下:
package com.ysd.springboot.quartz;35
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.ysd.springboot.config.MyTask;
@Component
@EnableScheduling //启动定时任务
public class SimpleTask {
@Autowired
private MyTask myTask;
@Resource
private SimpleDateFormat dateFormat;
@Scheduled(fixedRate = 1000 * 3) //每隔三秒
public void reportCurrentTime(){
myTask.say();//执行任务方法
System.out.println ("每隔3秒任务调度一次 现在时间 " + dateFormat.format (new Date
()));
}
//每隔5秒(cron表达式,六个*【*/5算一个,?算一个】,从左到右分别为秒分时天月年)
@Scheduled(cron = "*/5 * * * * ? ")
public void reportCurrentByCron(){
System.out.println ("每隔5秒任务调度一次 Scheduling Tasks Examples By Cron: The time is
now " + dateFormat.format (new Date ()));
}
}

备注: cron = "*/5 * * * * ? "表达式表示秒分时日月年。 */5 表示每隔 5 秒。
在任务类中使用了两个注解@EnableScheduling 和@Scheduled(Cron 表达式)。 具体作用如下:
⚫ @EnableScheduling:放在类前,标注启动定时任务;36
⚫ @Scheduled(表达式): 放在方法前,定义某个定时任务;

  1. 最后定义主模块启动类,启动测试即可。在控制台的结果如下图:
    在这里插入图片描述

Cron 表达式

cron 的表达式是字符串,实际上是由七个由空格分开的子表达式组成:
在这里插入图片描述

SpringBoot 集成 Mybatis 框架

SpringBoot 集成 Mybatis 的基本步骤

  1. 添加依赖;除了常规依赖外,需要加入 Mybatis 和 MySQL 依赖。
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-spring-boot}</version>
</dependency>
<!-- MySQL 连接驱动依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-connector}</version>
</dependency>
  1. 在 application.properties 配置文件中,配置数据源、 Mybatis 的配置及映射文件。
## 数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/库名
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
## Mybatis 配置
# 实体所在包,起别名
mybatis.typeAliasesPackage=org.spring.springboot.domain
# 映射文件所在路径
mybatis.mapperLocations=classpath:mapper/*.xml
  1. 在主模块上注解扫描接口包,使用@MapperScan(“包名”)。
@SpringBootApplication // Spring Boot 应用的标识
@MapperScan("org.spring.springboot.dao") // mapper 接口类扫描包配置
//如果要显示Sql细节还需要在logback配置<logger name="接口类所在包" level="debug" />
public class Application {
public static void main(String[] args) {
// 程序启动入口
// 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
SpringApplication.run(Application.class,args);
}
}

开启事务管理

SpringBoot 开启事务非常简单,只需要在业务层加注解@Transactional 就可以了。 具体方法如下:
⚫ 在设计 service 层的时候,我们应该合理的抽象出方法包含的内容,然后将方法用@Trasactional 注解
注释,默认在抛出 Exception.class 异常的时候,就会触发方法中所有数据库操作回滚,当然这指的是
增、删、改。
⚫ SpringBoot2.0 之前的版本需要在 Application 类中添加@EnableAutoConfiguration 或者
@EnableTransactionManagement 注解启动事务, 2.0 版本之后不需要加这些注解即可实现。
下面以转帐业务为例介绍事务管理控制:

1)、数据库表准备如下:

DROP TABLE IF EXISTS tbl_account;
CREATE TABLE tbl_account (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(20) NOT NULL,
balance float,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
insert into tbl_account(id,name,balance) values(1, 'andy','200');
insert into tbl_account(id,name,balance) values(2, 'lucy','300');

2)、 编写实体类,dao,service,controller,mapper 等
实体类 :

public class Account {
private int id;
private String name;
private float balance;
public Account() {
}
// 省略setter / getter
}

dao 层:

public interface AccountDao {
public void moveIn(@Param("id") int id, @Param("money") float money); // 转入
public void moveOut(@Param("id") int id, @Param("money") float money); // 转出43
}
Service 层:
public interface AccountService {
//转账
public void transfer(int outter,int inner,Integer money);
}

为了模拟转帐失败,我们在 service 实现类的转帐方法中抛出一个异常,并在 service 实现类的方法上添加
@Transactional 注解, 以此来声明一个事务:

@Service
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
@Transactional //开启事务
public void transfer(int outter, int inner, Integer money) {
accountDao.moveOut(outter, money); //转出
//为测试转帐失败,此处抛出异常,用事务进行控制
int i = 1/0; // 抛出异常
accountDao.moveIn(inner, money); //转入
}
}

Controller:

@RestController
@RequestMapping(value = "/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/transfer")
public String test(){
try {
// andy 给lucy转账50元
accountService.transfer(1, 2, 50);44
return "转账成功";
} catch (Exception e) {
e.printStackTrace();
return "转账失败";
}
}
}

Mapper:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.ysd.dao.AccountDao">
<!-- 转入 -->
<update id="moveIn" >
update tbl_account
set balance = balance + #{money }
where id= #{id,jdbcType=INTEGER}
</update>
<!-- 转出 -->
<update id="moveOut" >
update tbl_account
set balance = balance - #{money }
where id= #{id,jdbcType=INTEGER}
</update>
</mapper>

3)、 在 application.properties 配置文件中添加对 mapper 文件的扫描,前面案例已有,不再列出。
4)、 在启动类上添加@MapperScan 对相关包进行扫描

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.ysd.*.dao")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

测试运行,我们会发现转帐失败,数据库中仍然是转帐前的金额。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值