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

相关推荐
q***4282几秒前
Redis 设置密码(配置文件、docker容器、命令行3种场景)
数据库·redis·docker
Y***K4345 分钟前
后端缓存策略设计,多级缓存架构实践
缓存·架构
运维行者_25 分钟前
网站出现 525 错误(SSL 握手失败)修复指南
服务器·网络·数据库·redis·网络协议·bootstrap·ssl
fruge33 分钟前
openGauss数据库实操过程:从环境搭建到连接配置,第三方软件进行数据库管理
数据库·oracle
5***79001 小时前
后端服务监控面板,关键业务指标
数据库
倔强的石头_3 小时前
面向电力生产调度系统的数据库实践:从时序处理到多中心容灾
数据库
q***47183 小时前
MySQL 篇 - Java 连接 MySQL 数据库并实现数据交互
java·数据库·mysql
杨云龙UP3 小时前
【MySQL逻辑备份】基于mysqldump的MySQL 8.0全量逻辑备份脚本
linux·运维·数据库·sql·mysql·mssql
一只爱学习的小鱼儿3 小时前
QT中3D的使用
开发语言·数据库·qt
q***96584 小时前
Spring Boot 各种事务操作实战(自动回滚、手动回滚、部分回滚)
java·数据库·spring boot