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的原子存储了。

相关推荐
__土块__2 分钟前
一次电商秒杀系统架构评审:从本地锁到分布式锁的演进与取舍
java·redis·高并发·分布式锁·redisson·架构设计·秒杀系统
jarvisuni14 分钟前
GLM-5V-Turbo多模态测试,克隆Claude官网!
数据库
Full Stack Developme43 分钟前
MySQL 触发器 存储过程 介绍
数据库·mysql
杨云龙UP1 小时前
MySQL慢查询日志暴涨导致磁盘告警:slow query log膨胀至397G的生产故障排查:清理、参数优化
linux·运维·服务器·数据库·mysql
小旭95271 小时前
Spring Data Redis 从入门到实战:简化 Redis 操作全解析
java·开发语言·spring boot·redis·spring
Bat U1 小时前
MySQL数据库|视图+索引
数据库·mysql
无责任此方_修行中2 小时前
Redis 的"三面"人生:开源世界的权力转移
redis·后端·程序员
SQVIoMPLe2 小时前
[拆解LangChain执行引擎]以Actor模型的视角来看Pregel
服务器·数据库·langchain
你都会上树?2 小时前
Ubuntu22 安装PostgreSQL
数据库·postgresql
想唱rap2 小时前
线程之条件变量和生产消费模型
java·服务器·开发语言·数据库·mysql·ubuntu