SpringBoot使用redis生成訂單號(hào)的實(shí)現(xiàn)示例
項(xiàng)目場(chǎng)景:
在開發(fā)電商系統(tǒng)等需要生成唯一訂單號(hào)的應(yīng)用程序中,我們經(jīng)常會(huì)遇到需要生成唯一訂單號(hào)的需求。本文將介紹如何使用Spring Boot和Redis來(lái)生成唯一的訂單號(hào),并提供相應(yīng)的代碼示例。
在開始之前,需要確保已經(jīng)安裝并配置好了Java開發(fā)環(huán)境、Spring Boot框架和Redis數(shù)據(jù)庫(kù)。
解決方案:
訂單號(hào)生成規(guī)則: DD+年月日+5位流水號(hào),流水號(hào)當(dāng)天有效,第二天重新計(jì)數(shù)。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.concurrent.TimeUnit; /** * redis的increment 遞增方法 | 處理防重復(fù)和并發(fā)問(wèn)題 */ @Component public class OrderNumberCodeUtils { private static final String PREFIX = "DD"; private static final String DATE_FORMAT = "yyyyMMdd"; private static final String ORDER_SERIAL_NUMBER = "order_serial_number"; private static RedisTemplate redisTemplate; @Autowired public void redisTemplate(RedisTemplate redisTemplate){ OrderNumberCodeUtils.redisTemplate = redisTemplate; } public static String generateOrderNumber() { StringBuffer stringBuffer = new StringBuffer(); stringBuffer.append(PREFIX); // 獲取當(dāng)前日期 SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); String currentDate = dateFormat.format(new Date()); stringBuffer.append(currentDate); // 獲取流水號(hào) Long increment = redisTemplate.opsForValue().increment(ORDER_SERIAL_NUMBER, 1); /** * 返回值過(guò)期時(shí)間,單位為秒。 * 如果返回-2,則表示該鍵不存在; * 如果返回-1,則表示該鍵沒(méi)有設(shè)置過(guò)期時(shí)間; */ Long expire = redisTemplate.getExpire(ORDER_SERIAL_NUMBER, TimeUnit.SECONDS); if(expire == -1){ // 獲取距離當(dāng)天結(jié)束的秒數(shù) LocalDateTime endOfDay = LocalDate.now().atTime(23, 59, 59); long secondsToMidnight = LocalDateTime.now().until(endOfDay, ChronoUnit.SECONDS); //初始設(shè)置過(guò)期時(shí)間 redisTemplate.expire(ORDER_SERIAL_NUMBER, secondsToMidnight, TimeUnit.SECONDS); } String format = String.format("%05d", increment); stringBuffer.append(format); return stringBuffer.toString(); } }
到此這篇關(guān)于SpringBoot使用redis生成訂單號(hào)的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)SpringBoot redis生成訂單號(hào)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java配置dbcp連接池(數(shù)據(jù)庫(kù)連接池)示例分享
java配置dbcp連接池示例分享,大家參考使用吧2013-12-12java中synchronized關(guān)鍵字的3種寫法實(shí)例
synchronized是Java中的關(guān)鍵字,是一種同步鎖,下面這篇文章主要給大家介紹了關(guān)于java中synchronized關(guān)鍵字的3種寫法,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2021-11-11SpringBoot框架實(shí)現(xiàn)支付和轉(zhuǎn)賬功能
在 Spring Boot 框架中實(shí)現(xiàn)支付和轉(zhuǎn)賬功能時(shí),涉及到多個(gè)細(xì)節(jié)和注意點(diǎn),這些功能通常需要高度的安全性、穩(wěn)定性和可擴(kuò)展性,本文介紹了實(shí)現(xiàn)支付和轉(zhuǎn)賬功能的一些關(guān)鍵點(diǎn),需要的朋友可以參考下2024-08-08

Java控制臺(tái)實(shí)現(xiàn)猜拳游戲小游戲

java jdk1.8 使用stream流進(jìn)行l(wèi)ist 分組歸類操作

詳解 Java繼承關(guān)系下的構(gòu)造方法調(diào)用