偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

SpringBoot 七種定時任務解決方案

開發(fā) 后端
本文介紹了在SpringBoot中實現(xiàn)定時任務的7種不同解決方案,每種方案都有其特定的應用場景和優(yōu)缺點,開發(fā)者可以根據(jù)實際需求選擇合適的方案。

在現(xiàn)代后端開發(fā)中,定時任務是一個常見且重要的功能需求。從訂單自動取消到定時通知,再到數(shù)據(jù)匯總,定時任務幾乎無處不在。本文將介紹在SpringBoot中實現(xiàn)定時任務的7種不同解決方案,涵蓋單點定時任務和分布式定時任務兩大類。

定時任務,顧名思義,就是按照預定的時間間隔或特定的時間點執(zhí)行的任務。在Java生態(tài)系統(tǒng)中,有多種方式可以實現(xiàn)定時任務,每種方式都有其特定的應用場景和優(yōu)缺點。

單點定時任務

1. JDK原始方案

自JDK 1.5起,Java提供了ScheduledExecutorService接口,用于替代老舊的Timer類。ScheduledExecutorService提供了更可靠和靈活的定時任務執(zhí)行能力。

操作步驟:

  • 創(chuàng)建一個ScheduledExecutorService實例。
  • 使用scheduleAtFixedRate或scheduleWithFixedDelay方法安排任務。
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.Date;

public class SomeScheduledExecutorService {
    public static void main(String[] args) {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
        scheduledExecutorService.scheduleAtFixedRate(() -> {
            System.out.println("執(zhí)行任務:" + new Date());
        }, 1, 30, TimeUnit.SECONDS);
    }
}

2. Spring Task

Spring Framework提供了內(nèi)置的定時任務支持,通過@Scheduled注解和@EnableScheduling注解可以非常方便地配置定時任務。

操作步驟:

  • 在啟動類上添加@EnableScheduling注解。
  • 在需要定時執(zhí)行的方法上添加@Scheduled注解,并配置cron表達式。

代碼示例:

import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

@Component
@EnableScheduling
public class SomeJob {
    @Scheduled(cron = "0 0/1 * * * ? *")
    public void someTask() {
        System.out.println("每分鐘執(zhí)行一次任務: " + LocalDateTime.now());
    }}

3. 基于Redis實現(xiàn)

Redis也可以用來實現(xiàn)定時任務,通過利用Redis的ZSet和鍵空間通知功能,可以實現(xiàn)高效的定時任務調(diào)度。

操作步驟:

  • 使用Redis的ZSet存儲定時任務。
  • 使用Redis的鍵空間通知功能監(jiān)聽任務過期事件。

代碼示例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.Instant;
import java.util.Set;

@Configuration
@EnableScheduling
public class RedisJob {
    public static final String JOB_KEY = "redis.job.task";
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 添加任務
    public void addTask(String task, Instant instant) {
        stringRedisTemplate.opsForZSet().add(JOB_KEY, task, instant.getEpochSecond());
    }

    // 定時任務隊列消費
    @Scheduled(cron = "0 0/1 * * * ? *")
    public void doDelayQueue() {
        long nowSecond = Instant.now().getEpochSecond();
        Set<String> tasks = stringRedisTemplate.opsForZSet().range(JOB_KEY, 0, nowSecond);
        for (String task : tasks) {
            System.out.println("執(zhí)行任務: " + task);
        }
        stringRedisTemplate.opsForZSet().remove(JOB_KEY, 0, nowSecond);
    }

    // 自定義監(jiān)聽器
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
                                            MessageListenerAdapter listenerAdapter) {

        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.addMessageListener(listenerAdapter, new PatternTopic("__keyevent@*__:expired"));
        return container;
    }

    @Bean
    MessageListenerAdapter listenerAdapter(KeyExpiredListener receiver) {
        return new MessageListenerAdapter(receiver, "onMessage");
    }

    @Bean
    KeyExpiredListener keyExpiredListener() {
        return new KeyExpiredListener();
    }
}

class KeyExpiredListener extends KeyExpirationEventMessageListener {
    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 處理過期任務
        String expiredKey = message.getBody();
        System.out.println("Redis鍵過期: " + new String(expiredKey));
    }
}

分布式定時任務

在分布式系統(tǒng)中,單個節(jié)點執(zhí)行定時任務可能會遇到數(shù)據(jù)不一致、任務重復執(zhí)行等問題。因此,需要使用分布式定時任務框架。

4. Quartz

Quartz是一個功能強大的開源任務調(diào)度框架,支持復雜的定時規(guī)則和任務管理。

操作步驟:

  • 添加Quartz依賴。
  • 配置Quartz Scheduler。
  • 編寫Job類和Trigger。

代碼示例(略,具體配置和代碼可以參考Quartz官方文檔)。

5. elastic-job-lite

elastic-job-lite是當當網(wǎng)開源的一個分布式任務調(diào)度框架,支持分片、容錯等功能。

操作步驟:

  • 添加elastic-job-lite依賴。
  • 配置作業(yè)中心和注冊中心。
  • 編寫作業(yè)實現(xiàn)類。

6. LTS

LTS(Light Task Scheduler)是一個分布式任務調(diào)度框架,支持任務的高可用、可擴展和可監(jiān)控。

操作步驟(略,具體配置和代碼可以參考LTS官方文檔)。

7. XXL-JOB

XXL-JOB是一個分布式任務調(diào)度平臺,支持任務的高可用、動態(tài)管理、任務失敗重試等功能。

操作步驟:

  • 部署XXL-JOB管理后臺。
  • 添加XXL-JOB客戶端依賴。
  • 配置XXL-JOB執(zhí)行器。
  • 編寫任務執(zhí)行邏輯。

總結(jié)

本文介紹了在SpringBoot中實現(xiàn)定時任務的7種不同解決方案,包括JDK原始方案、Spring Task、基于Redis實現(xiàn)、Quartz、elastic-job-lite、LTS和XXL-JOB。每種方案都有其特定的應用場景和優(yōu)缺點,開發(fā)者可以根據(jù)實際需求選擇合適的方案。在實際項目中,選擇適合的定時任務解決方案,不僅可以提高開發(fā)效率,還可以確保系統(tǒng)的穩(wěn)定性和可靠性。

責任編輯:趙寧寧 來源: Java技術(shù)營地
相關(guān)推薦

2021-09-26 09:17:01

Python命令定時任務

2022-03-24 12:15:50

MySQL數(shù)據(jù)庫讀寫分離

2024-01-31 08:38:57

Python定時任務函數(shù)

2021-11-22 12:35:40

Python命令定時任務

2022-03-30 07:52:16

.NET應用程序C#

2021-11-29 09:15:57

Github網(wǎng)絡Python

2024-09-20 05:49:04

SpringBoot后端

2021-06-30 07:19:34

SpringBoot定時任務

2025-04-15 08:15:00

setTimeout代碼

2024-12-02 14:30:20

2022-12-13 10:05:27

定時任務任務調(diào)度操作系統(tǒng)

2024-01-22 08:53:00

策略任務RocketMQ

2024-02-26 11:12:33

定時任務線程

2022-12-30 17:52:44

分布式容錯架構(gòu)

2024-07-31 14:03:00

Spring定時任務管理

2024-08-01 11:38:40

2023-09-19 15:33:50

Web實時消息推送

2018-07-17 09:00:00

初創(chuàng)企業(yè)任務管理工具nTask

2010-10-15 10:02:01

Mysql表類型

2025-05-13 08:20:58

點贊
收藏

51CTO技術(shù)棧公眾號