Spring Boot延迟执行实现

news2025/2/25 5:53:36

说明:本文介绍如何在Spring Boot项目中,延迟执行某方法,及讨论延迟执行方法的是事务问题。

搭建Demo

首先,创建一个Spring Boot项目,pom.xml如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/>
    </parent>

    <groupId>com.hezy</groupId>
    <artifactId>delay_thread_demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>



        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>
    </dependencies>
</project>

写个接口,打印进入方法时的时间

import com.hezy.service.DelayService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/demo")
@Log4j2
public class DemoController {

    @Autowired
    private DelayService delayService;

    @GetMapping
    public String demo() {
        return "Hello World!";
    }

    @GetMapping("/delay1/{time}")
    public String delay1(@PathVariable Integer time) {
        log.info("enter delay1...date={} time={}",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
        delayService.delay1(time);
        return "success";
    }
}

延迟执行实现

delayService,delay1()实现,如下:

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    /**
     * 延迟执行
     * @param time
     */
    public void delay1(Integer time) {
        scheduler.schedule(() -> {
            log.info("run delay1...date={} time={}",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
        }, time, TimeUnit.SECONDS);
    }

就是开了一个线程来执行,可设置延迟时间。启动项目,测试,如下:

(发送请求,响应结果即刻返回)

在这里插入图片描述

(控制台可见任务延迟5秒执行)

在这里插入图片描述

事务问题

写个实体类

import lombok.Data;

@Data
public class User {

    private Integer id;

    private String username;

    private String password;
}

再写个Mapper,里面写个insert()方法

import com.hezy.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface UserMapper {

    @Insert("insert into user (id, username, password) values (#{id}, #{username}, #{password})")
    void insert(User user);
}

新建个延迟方法,delay2(),方法生加声明式注解,方法内手动制造一个异常

(controller)

    @PostMapping("/delay2/{time}")
    public String delay2(@RequestBody User user, @PathVariable Integer time) {
        log.info("enter delay2...date={} time={}",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
        delayService.delay2(user, time);
        return "success";
    }

(service)

    /**
     * 声明式事务
     */
    @Transactional(rollbackFor = Exception.class)
    public void delay2(User user, Integer time) {
        scheduler.schedule(() -> {
            log.info("run delay2...date={} time={}",
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
            userMapper.insert(user);
            
            int i = 1 / 0;
            
            user.setId(3);
            userMapper.insert(user);
        }, time, TimeUnit.SECONDS);
    }

启动项目,调用方法

在这里插入图片描述

控制台没有报错

在这里插入图片描述

数据库,插入了一条数据,事务没有控制住

在这里插入图片描述

以上说明,声明式事务无法控制延迟执行的方法,并且异常也被线程内捕获了,没有抛出来。

编程式事务

试下编程式事务,手动实现事务,如下:

(controller)

    @PostMapping("/delay3/{time}")
    public String delay3(@RequestBody User user, @PathVariable Integer time) {
        log.info("enter delay3...date={} time={}",
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
        delayService.delay3(user, time);
        return "success";
    }

(service)

    @Autowired
    private PlatformTransactionManager transactionManager;

    /**
     * 编程式事务
     */
    public void delay3(User user, Integer time) {
        scheduler.schedule(() -> {
            TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
            try {
                log.info("run delay3...date={} time={}",
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), time);
                userMapper.insert(user);

                // 故意产生异常
                int i = 1 / 0;

                user.setId(3);
                userMapper.insert(user);

                // 提交事务
                transactionManager.commit(status);
            } catch (Exception e) {
                transactionManager.rollback(status);
                e.printStackTrace();
            }
        }, time, TimeUnit.SECONDS);
    }

把数据库记录删掉,启动项目,测试

在这里插入图片描述

控制台报错

在这里插入图片描述

数据库没有插入记录,编程式事务控制住了

在这里插入图片描述

总结

本文介绍了在Spring Boot项目中延迟执行方法的实现,以及延迟执行下声明式事务和编程式事务的使用情况。

完整源码:https://github.com/HeZhongYing/delay_thread_demo

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2304723.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

npm i 失败权限问题

安装完node之后, 测试全局安装一个最常用的 express 模块进行测试 失败&#xff0c;但是用管理员权限打开cmd 安装就成功。 报错如下&#xff1a; npm ERR! If you believe this might be a permissions issue, please double-check the npm ERR! permissions of the file and …

uniapp 微信小程序打包之后vendor.js 主包体积太大,解决办法,“subPackages“:true设置不生效

现在是打包的时候&#xff0c;vendor.js 的内容全部打到了主包里面&#xff0c; 说一下我的方法&#xff1a; 1. 通过发行 小程序打包 这样打包的体积是最小的&#xff0c;打包之后打开微信开发工具&#xff0c;然后再上传 2.manifest.json,在“mp-weixin”里添加代码 "…

23.2、云计算安全机制与案例分析

目录 云计算安全保护机制与技术方案云计算安全保护机制与技术方案常见云计算网络安全机制云计算安全管理与运维云计算安全综合应用案例分析 - 阿里云云计算安全综合应用案例分析 - 腾讯云云计算安全综合应用案例分析 - 华为云 云计算安全保护机制与技术方案 首先针对云计算&am…

游戏引擎学习第120天

仓库:https://gitee.com/mrxiao_com/2d_game_3 上次回顾&#xff1a;周期计数代码 我们正在进行一个项目的代码优化工作&#xff0c;目标是提高性能。当前正在优化某个特定的代码片段&#xff0c;已经将其执行周期减少到48个周期。为了实现这一目标&#xff0c;我们设计了一个…

将DeepSeek接入vscode的N种方法

接入deepseek方法一:cline 步骤1:安装 Visual Studio Code 后,左侧导航栏上点击扩展。 步骤2:搜索 cline,找到插件后点击安装。 步骤3:在大模型下拉菜单中找到deep seek,然后下面的输入框输入你在deepseek申请的api key,就可以用了 让deepseek给我写了一首关于天气的…

AI智算-k8s+SGLang实战:DeepSeek-r1:671b满血版多机多卡私有化部署全攻略

k8sSGLang实战&#xff1a;DeepSeek-r1:671b满血版多机多卡私有化部署全攻略 前言环境准备1. 模型下载2.软硬件环境介绍 正式部署1. 部署LWS API2. 通过 LWS 部署DeepSeek-r1模型3. 查看显存占用情况4. 服务对外暴露5. 测试部署效果5.1 通过 curl5.2 通过 OpenWebUIa. 部署 Ope…

【蓝桥杯单片机】第十三届省赛第二场

一、真题 二、模块构建 1.编写初始化函数(init.c) void Cls_Peripheral(void); 关闭led led对应的锁存器由Y4C控制关闭蜂鸣器和继电器 2.编写LED函数&#xff08;led.c&#xff09; void Led_Disp(unsigned char ucLed); 将ucLed取反的值赋给P0 开启锁存器 关闭锁存…

从零开始玩转TensorFlow:小明的机器学习故事 5

图像识别的挑战 1 故事引入&#xff1a;小明的“图像识别”大赛 小明从学校里听说了一个有趣的比赛&#xff1a;“美食图像识别”。参赛者需要训练计算机&#xff0c;看一张食物照片&#xff08;例如披萨、苹果、汉堡等&#xff09;&#xff0c;就能猜出这是什么食物。听起来…

sql的索引与性能优化相关

之前面试的时候&#xff0c;由于在简历上提到优化sql代码&#xff0c;老是会被问到sql索引和性能优化问题&#xff0c;用这个帖子学习记录一下。 1.为什么要用索引 ------------------------------------------------------------------------------------------------------…

碰撞检测 | 图解凸多边形分离轴定理(附ROS C++可视化)

目录 0 专栏介绍1 凸多边形碰撞检测2 多边形判凸算法3 分离轴定理(SAT)4 算法仿真与可视化4.1 核心算法4.2 仿真实验 0 专栏介绍 &#x1f525;课设、毕设、创新竞赛必备&#xff01;&#x1f525;本专栏涉及更高阶的运动规划算法轨迹优化实战&#xff0c;包括&#xff1a;曲线…

计算机网络真题练习(高软29)

系列文章目录 计算机网络阶段练习 文章目录 系列文章目录前言一、真题练习总结 前言 计算机网络的阶段练习题&#xff0c;带解析答案。 一、真题练习 总结 就是高软笔记&#xff0c;大佬请略过&#xff01;

DPVS-1:编译安装DPVS (ubuntu22.04)

操作系统 rootubuntu22:~# lsb_release -a No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 22.04.3 LTS Release: 22.04 Codename: jammy rootubuntu22:~# 前置软件准备 apt install git apt install meson apt install gcc ap…

EasyRTC:全平台支持与自研算法驱动的智能音视频通讯解决方案

在智能硬件的浪潮中&#xff0c;设备之间的互联互通已成为提升用户体验的核心需求。无论是智能家居、智能办公&#xff0c;还是工业物联网&#xff0c;高效的音视频通讯和交互能力是实现智能化的关键。然而&#xff0c;传统音视频解决方案往往面临平台兼容性差、交互体验不佳以…

Elasticsearch 自动补全搜索 - autocomplete

作者&#xff1a;来自 Elastic Amit Khandelwal 探索处理自动完成的不同方法&#xff0c;从基础到高级&#xff0c;包括输入时搜索、查询时间、完成建议器和索引时间。 在本文中&#xff0c;我们将介绍如何避免严重的性能错误、Elasticsearch 默认解决方案为何不适用以及重要的…

快速入门Springboot+vue——MybatisPlus多表查询及分页查询

学习自哔哩哔哩上的“刘老师教编程”&#xff0c;具体学习的网站为&#xff1a;7.MybatisPlus多表查询及分页查询_哔哩哔哩_bilibili&#xff0c;以下是看课后做的笔记&#xff0c;仅供参考。 多表查询 多表查询[Mybatis中的]&#xff1a;实现复杂关系映射&#xff0c;可以使…

工程师 - VSCode的AI编码插件介绍: MarsCode

豆包 MarsCode MarsCode AI: Coding Assistant Code and Innovate Faster with AI 豆包 MarsCode - 编程助手 安装完成并使能后&#xff0c;会在下方状态栏上显示MarsCode AI。 安装完并重启VSCode后&#xff0c;要使用这个插件&#xff0c;需要注册一下账号。然后授权VSCod…

VOS3000线路对接、路由配置与路由分析操作教程

一、VOS3000简介 VOS3000是一款常用的VoIP运营平台&#xff0c;支持多种线路对接和路由配置&#xff0c;适合新手快速上手。本教程将带你了解如何对接线路、配置路由以及进行路由分析。 二、线路对接 准备工作 获取线路信息&#xff1a;从供应商处获取线路的IP地址、端口、用…

学习Linux准备2

使用win10系统带的wsl配置ubuntu系统&#xff0c;通过wsl功能我们可以更简单更轻松的获得Linux系统环境。 首先开启Windows自带的wsl功能 打开控制面板&#xff0c;选中启用或关闭Windows功能 这里我们点击进入 将上图红√点击上&#xff0c;点击确定&#xff0c;然后重新启动…

四、综合案例(Unity2D)

一、2D渲染 1、2D相机基本设置 上面是透视&#xff0c;下面是正交 2、图片资源 在Unity中&#xff0c;常规图片导入之后&#xff0c;一般不在Unity中直接使用&#xff0c;而是转为精灵图Sprite 将图片更改为即可使用Unity内置的图片切割功能 无论精灵图片是单个的还是多个的…

Codes 开源免费研发项目管理平台 2025年第一个大版本3.0.0 版本发布及创新的轻IPD实现

Codes 简介 Codes 是国内首款重新定义 SaaS 模式的开源项目管理平台&#xff0c;支持云端认证、本地部署、全部功能开放&#xff0c;并且对 30 人以下团队免费。它通过创新的方式简化研发协同工作&#xff0c;使敏捷开发更易于实施。并提供低成本的敏捷开发解决方案&#xff0…