search
HomeDatabaseRedisHow Redis implements order expiration deletion

Foreword

The design order has expired, you cannot rely solely on Redis, you need a cover-up strategy

Code implementation:

import com.coolplay.trade.dto.req.CancelOrderReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Set;
import java.util.concurrent.TimeUnit;


@Service
@Slf4j
public class OrderRedisDelayQueueOperator extends AbstractOrderScheduleDelayQueue {
    @Resource(name = "redisTemplate")
    private ZSetOperations<String, String> orderRedis;

    /**
     * 预售、现货生成订单15分钟后未支付,需要取消订单
     */
    private static final String DELAY_QUEUE_NAME = "order";

    /**
     * 每1秒执行一次
     */
    @Override
    @Scheduled(cron = "0/1 * * * * ? ")
    public void orderEventProcess() {
        if (!redisLock.tryLock(this.getClass().getSimpleName(), TimeUnit.MILLISECONDS, 10, 100)) {
            return;
        }
        Set<String> dq = orderRedis.range(DELAY_QUEUE_NAME, 0L, Long.MAX_VALUE);
        if (CollectionUtils.isEmpty(dq)) {
            return;
        }
        for (String orderNo : dq) {
            Double xs = orderRedis.score(DELAY_QUEUE_NAME, orderNo);
            Double now = System.currentTimeMillis() * 1.0;
            if (xs <= now) {
                log.info("{} timed out", orderNo);
                super.threadPoolTaskExecutor.execute(() -> {
                    CancelOrderReq req = new CancelOrderReq();
                    req.setOrderNo(orderNo);
                    req.setCancelType(OrderActionEnum.TIME_OUT_CANCEL);
                    orderService.cancelOrder(req);
                });
            } else {
                //log.info("{} no time out", orderNo);
                //如果最小的都没有过期,剩余的则不用处理了
                break;
            }
        }
    }


    public void addToRedis(String orderNo, long delayTime) {
        orderRedis.add(DELAY_QUEUE_NAME, orderNo, delayTime * 1.0);

    }

    public void removeFromRedis(String orderNo) {

        orderRedis.remove(DELAY_QUEUE_NAME, orderNo);
    }
}

Back-up strategy

/**
     * 取消订单--10分钟--20分钟执行一次
     */
    @XxlJob("cancelOrder20Minutes")
    public void cancelOrderTenMinutes() {
        log.info("*****[开始:下单十分钟以后系统自动取消订单]*****");
        Date start = DateUtil.dateRoll(new Date(), Calendar.MINUTE,-20);
        Date end = new Date();
       List<ClOrder> clorderList =clOrderMapper.selectListAllOrdrWaiting(start,end);
       if(ObjectUtil.isNotEmpty(clorderList)){
           for(int i=0;i<clorderList.size();i++){
               ClOrder clOrder = clorderList.get(i);
               if(ObjectUtil.isNotEmpty(clOrder)){
                   Date orderTime = clOrder.getOrderTime();
                   long between = cn.hutool.core.date.DateUtil.between(orderTime, new Date(), DateUnit.MINUTE);
                   if(between>10){
                       ClOrder clOrderTemp = new ClOrder();
                       clOrderTemp.setOrderState("3");
                       clOrderTemp.setId(clOrder.getId());
                       clOrderTemp.setMemberId(clOrder.getMemberId());
                       String msg="您的订单已经取消,订单金额已发放至您的账户请查收~";
                       try {
                           boolean b = orderService.cancelOrder(clOrderTemp,msg);
                           if(!b){
                               log.info("[订单失效:定时任务兜底策略更新失败]**订单ID: {}",clOrderTemp.getId());
                           }
                           log.info("[Redis订单取消订单失效,定时任务兜底策略生效]");
                       }catch (Exception e){
                           log.info("[订单失效:定时任务兜底策略更新失败]**订单ID: {}",clOrderTemp.getId());
                           e.printStackTrace();
                       }


                   }
               }
           }
       }
        log.info("*****[结束:下单十分钟以后系统自动取消订单]*****");
    }

The above is the detailed content of How Redis implements order expiration deletion. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
Redis: Exploring Its Core Functionality and BenefitsRedis: Exploring Its Core Functionality and BenefitsApr 30, 2025 am 12:22 AM

Redis's core functions include memory storage and persistence mechanisms. 1) Memory storage provides extremely fast read and write speeds, suitable for high-performance applications. 2) Persistence ensures that data is not lost through RDB and AOF, and the choice is based on application needs.

Redis's Server-Side Operations: What It OffersRedis's Server-Side Operations: What It OffersApr 29, 2025 am 12:21 AM

Redis'sServer-SideOperationsofferFunctionsandTriggersforexecutingcomplexoperationsontheserver.1)FunctionsallowcustomoperationsinLua,JavaScript,orRedis'sscriptinglanguage,enhancingscalabilityandmaintenance.2)Triggersenableautomaticfunctionexecutionone

Redis: Database or Server? Demystifying the RoleRedis: Database or Server? Demystifying the RoleApr 28, 2025 am 12:06 AM

Redisisbothadatabaseandaserver.1)Asadatabase,itusesin-memorystorageforfastaccess,idealforreal-timeapplicationsandcaching.2)Asaserver,itsupportspub/submessagingandLuascriptingforreal-timecommunicationandserver-sideoperations.

Redis: The Advantages of a NoSQL ApproachRedis: The Advantages of a NoSQL ApproachApr 27, 2025 am 12:09 AM

Redis is a NoSQL database that provides high performance and flexibility. 1) Store data through key-value pairs, suitable for processing large-scale data and high concurrency. 2) Memory storage and single-threaded models ensure fast read and write and atomicity. 3) Use RDB and AOF mechanisms to persist data, supporting high availability and scale-out.

Redis: Understanding Its Architecture and PurposeRedis: Understanding Its Architecture and PurposeApr 26, 2025 am 12:11 AM

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

Redis vs. SQL Databases: Key DifferencesRedis vs. SQL Databases: Key DifferencesApr 25, 2025 am 12:02 AM

The main difference between Redis and SQL databases is that Redis is an in-memory database, suitable for high performance and flexibility requirements; SQL database is a relational database, suitable for complex queries and data consistency requirements. Specifically, 1) Redis provides high-speed data access and caching services, supports multiple data types, suitable for caching and real-time data processing; 2) SQL database manages data through a table structure, supports complex queries and transaction processing, and is suitable for scenarios such as e-commerce and financial systems that require data consistency.

Redis: How It Acts as a Data Store and ServiceRedis: How It Acts as a Data Store and ServiceApr 24, 2025 am 12:08 AM

Redisactsasbothadatastoreandaservice.1)Asadatastore,itusesin-memorystorageforfastoperations,supportingvariousdatastructureslikekey-valuepairsandsortedsets.2)Asaservice,itprovidesfunctionalitieslikepub/submessagingandLuascriptingforcomplexoperationsan

Redis vs. Other Databases: A Comparative AnalysisRedis vs. Other Databases: A Comparative AnalysisApr 23, 2025 am 12:16 AM

Compared with other databases, Redis has the following unique advantages: 1) extremely fast speed, and read and write operations are usually at the microsecond level; 2) supports rich data structures and operations; 3) flexible usage scenarios such as caches, counters and publish subscriptions. When choosing Redis or other databases, it depends on the specific needs and scenarios. Redis performs well in high-performance and low-latency applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools