SpringBoot事务-调度-缓存

一.Spring Boot中的事务管理


  • 设置事务
    • @Transactional(isolation = Isolation.DEFAULT)
    • @Transactional(propagation = Propagation.REQUIRED)
  • 开启事务
    • @EnableTransactionManagement

整合springboot、mybatis-plus、lombok做了对顾客的简单的事务管理

代码演示:

1. 导入对应的依赖
<dependencies>
    <!--spring+springMVC-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

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

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>
2. 编写实体类Consume
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("consume")
public class Consume {
    @TableId(value = "cust_id" ,type = IdType.AUTO)
    private int custId;
    @TableField("cust_address")
    private String custAddress;
    @TableField("cust_level")
    private String custLevel;
    @TableField("cust_name")
    private String custName;
    @TableField("cust_phone")
    private String custPhone;

}
3. 新建一个mapper包,在包里新建一个ConsumeMapper接口
@Mapper
public interface ConsumeMapper  extends BaseMapper<Consume> {

}
4. 编写业务层代码以及实现类
public interface ICustomerService extends IService<Consume> {

    public void batchAdd();

}

@Service
public class CustomerServiceImp extends ServiceImpl<ConsumeMapper, Consume> implements ICustomerService {

    @Resource
    private ConsumeMapper mapper;
    
    @Transactional
    @Override
    public void batchAdd() {
        mapper.insert(new Consume(1,"台湾君越酒店","五星级","佩洛西1","12345678"));
        int a = 10/0;
        mapper.insert(new Consume(2,"台湾君越酒店","五星级","佩洛西1","12345678"));
        mapper.insert(new Consume(3,"台湾君越酒店","五星级","佩洛西1","12345678"));

    }
}

注意:在业务层的实现类添加了@Transactional注解,进行了事务管理

5. 编写控制层代码
@RestController
public class CustomerControllerImp {

    @Autowired
    private ICustomerService service;

    @RequestMapping("/add")
    public String batchAdd() {
        service.batchAdd();
        return "成功";
    }
}
6. 测试代码
@SpringBootApplication
@EnableTransactionManagement
public class Springboot01CenterTxApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot01CenterTxApplication.class, args);
    }

}

注意:在测试代码中一定要开启事务管理,

开启事务管理的注解:@EnableTransactionManagement

7. 测试结果:

观察结果我们会发现页面上会显示成功,同时我们会发现数据库表中也会新增三条数据

此时我们开启事务管理,同时模拟一个除0错的异常,我们继续观察结果会发现页面上会报错(500),同时数据库表中也只会新增模拟异常之前的一条数据

二、Spring Boot异步任务


在项目开发中,绝大多数情况下都是通过同步方式处理业务逻辑的,但是比如批量处理数据,批量发送邮件,批量发送短信等操作容易造成阻塞的情况,之前大部分都是使用多线程来完成此类任务而在Spring 3+之后,就已经内置了@Async注解来完美解决这个问题,从而提高效率。

  • 使用的注解
    • @EnableAsync 启动类上开启基于注解的异步任务
    • @Async 标识的方法会异步执行

代码演示:

1.ICustomerService
public interface ICustomerService {

    public void batchAdd();

}
2.CustomerServiceImp
@Service
public class CustomerServiceImp implements ICustomerService{


    @Override
    @Async
    public void batchAdd() {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("======>批量新增");
    }
}

注意:在方法上标@Async注解,表示该方法异步执行

3.CustomerControllerImp
@RestController
public class CustomerControllerImp {

    @Autowired
    private ICustomerService service;

    @RequestMapping("/add")
    public String batchAdd() {
        service.batchAdd();
        return "成功";
    }
}

4.测试代码

@SpringBootApplication
@EnableAsync//开启异步处理
public class Springboot02CenterAysncApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02CenterAysncApplication.class, args);
    }

}

注意:在测试代码中一定要开启异步处理,

开启异步处理的注解:@EnableAsync

5.测试结果:

观察结果我们会发现页面上会显示成功,同时我们会发现控制台有输出结果

三.SpringBoot定时任务调度


SpringTask

在项目开发中,经常需要执行一些定时任务,比如 每月1号凌晨需要汇总上个月的数据分析报表; 每天 凌晨分析前一天的日志信息等定时操作。Spring 为我们提供了异步执行定时任务调度的方式

  • 使用的注解
    • @EnableScheduling启动类上开启基于注解的定时任务
    • @Scheduled标识的方法会进行定时处理 需要通过 cron 属性来指定 cron 表达式:秒 分 时 日 月 星期 年 在线生成cron表达式 http://cron.qqe2.com/

代码演示:

1.MyJob
@Component
public class MyJob {
    @Scheduled(cron = "3/4 41 12 14 8 ? ")
    public void show(){
        System.out.println("甜甜开心"+ new Date());
    }
}

注意:在需要进行任务调度的方法上添加注解@Scheduled(cron = "3/4 41 12 14 8 ? ")

corn 里面的信息可以根据corn在线生成器获得

2.测试代码

@SpringBootApplication
@EnableScheduling//开启任务调度
public class Springboot03CenterJobApplication {

    public static void main(String[] args) {
        SpringApplication.run(Springboot03CenterJobApplication.class, args);
    }

}

注意:在测试代码中一定要开启任务调度,

开启任务调度的注解:@EnableScheduling

3.测试结果:

观察结果我们会发现每个4秒钟会被调度一次

四.SpringBoot 整合Mail


1. 第一步添加坐标
<!--导入jedis的包-->
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.2.0</version>
</dependency>
2. 第二步开启配置
2.1 编写配置文件application.properties
##配置邮箱信息
spring.mail.username=3418813089
spring.mail.password=dvhgkvhmqngtdaeh //QQ邮箱授权码
##发送邮件服务器
spring.mail.host=smtp.qq.com
#ssl\u8FDE\u63A5
spring.mail.properties.smtp.ssl.enable=true

此处我们以扣扣邮箱作为发送方的邮箱

2.2 QQ邮箱授权码的查看步骤

3. 第三步编写代码
package com.ztt.springboot_04_center_mail;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import redis.clients.jedis.Jedis;

import javax.mail.internet.MimeMessage;
import java.io.File;

@SpringBootTest
class Springboot04CenterMailApplicationTests {

    @Autowired(required = false)
    private JavaMailSenderImpl javaMailSender;

    //发送简单邮件
    @Test
    void show1() {
        //1.创建邮件对象
        SimpleMailMessage simpleMailMessage =   new SimpleMailMessage();
        //2.设置信息
        simpleMailMessage.setSubject("甜甜不甜");
        simpleMailMessage.setText("啊啊啊啊啊学习使我快乐~~~");
        simpleMailMessage.setFrom("3418813089@qq.com");
        simpleMailMessage.setTo("1587154344@qq.com");
        //3.发送邮件
        javaMailSender.send(simpleMailMessage);
        System.out.println("发送成功~~~");
    }

    //发送复杂邮件
    @Test
    void show2()throws Exception {
        //1.创建邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //2.创建MimeMessageHelper
        MimeMessageHelper mimeMessageHelper =  new MimeMessageHelper(mimeMessage,true);
        //3.设置信息
        mimeMessageHelper.setSubject("程序员的误解");
        mimeMessageHelper.setText("程序员是个<span style='color:red'>高薪,高危</span>的职业",true);
        mimeMessageHelper.addAttachment("1.jpg",new File("E:\\壁紙\\1.jpg"));
        mimeMessageHelper.setFrom("3418813089@qq.com");
        mimeMessageHelper.setTo("1587154344@qq.com");
        //4.发送邮件
        javaMailSender.send(mimeMessage);
    }

    @Test
    public void show(){
        Jedis jedis=new Jedis("localhost" ,6379);
        System.out.println(jedis.ping());
    }

}

4.测试结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值