redis生成唯一流水id,自增

java 复制代码
package com.csgholding.pvgpsp.ums.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
public class CodeController {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 15 18位 前缀=当前日期=2018112921303030-5位自增id(高并发请下 先天性安全) 00001<br>
     * 00010<br>
     * 00100<br>
     * 01000<br>
     * 11000<br>
     * 在相同毫秒情况下,最多只能生成10万-1=99999订单号<br>
     * 假设:双11每毫秒99万笔 <br>
     * 提前生成号订单号码存放在redis中
     * <p>
     * 9.9万*1000=900万<br>
     * 考虑失效时间问题 24小时
     *
     * @return
     */
    // 基于Redis 实现分布式全局id
    @RequestMapping("/getCode")
    public String order(String key, String name) {
        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        long incrementAndGet = redisAtomicLong.incrementAndGet();
        // 6位
        String orderId = name + prefix() + String.format("%1$06d", incrementAndGet);
        return orderId;
    }

    //自增+sum个,暂时不要
//    @RequestMapping("/addCodeSum")
//    public String order1(String key,Integer sum) {
//        RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
//        // // 起始值
//        // redisAtomicLong.set(10);
//        // 设置步长加10
//        redisAtomicLong.addAndGet(sum);
//        return redisAtomicLong.incrementAndGet() + "";
//    }

    /**
     * @return 日期
     */
    public static String prefix() {
        String[] split = LocalDate.now().toString().split("-");
        String time = "";
        for (String s : split) {
            time += s;
        }
        return time;
    }

}

springBoot集成redis后,可以通过redis的单线程特性,来生成流水号,并且只要多个服务是用的同一个redis服务器,就不会存在重复问题。

我原本想的是用分布式锁来完成,后面发现不管怎么样,都得把计数器放在redis上,所以就直接用redis的原子存储了。

相关推荐
IvorySQL4 小时前
PostgreSQL 技术日报 (3月7日)|生态更新与内核性能讨论
数据库·postgresql·开源
赵渝强老师4 小时前
【赵渝强老师】金仓数据库的数据文件
数据库·国产数据库·kingbase·金仓数据库
随逸1778 小时前
《Milvus向量数据库从入门到实战,手把手搭建语义检索系统》
数据库
神秘的猪头8 小时前
🚀 React 开发者进阶:RAG 核心——手把手带你玩转 Milvus 向量数据库
数据库·后端·llm
IvorySQL1 天前
PostgreSQL 技术日报 (3月6日)|为什么 Ctrl-C 在 psql 里让人不安?
数据库·postgresql·开源
NineData1 天前
数据库管理工具NineData,一年进化成为数万+开发者的首选数据库工具?
运维·数据结构·数据库
JavaGuide1 天前
字节二面:Redis 能做消息队列吗?怎么实现?
redis·后端
漫霂1 天前
基于redis实现登录校验
redis·后端
程序员小崔日记1 天前
一篇文章彻底搞懂 MySQL 和 Redis:原理、区别、项目用法全解析(建议收藏)
redis·mysql·项目实战