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

相关推荐
土了个豆子的26 分钟前
03.缓存池
开发语言·前端·缓存·visualstudio·c#
少男的脸红藏不住心事30 分钟前
GD32入门到实战35--485实现OTA
数据库·mongodb·nosql
爬山算法1 小时前
Redis(50) Redis哨兵如何与客户端进行交互?
数据库·redis·交互
007php0071 小时前
某大厂MySQL面试之SQL注入触点发现与SQLMap测试
数据库·python·sql·mysql·面试·职场和发展·golang
YS_Geo2 小时前
Redis 深度解析:数据结构、持久化与集群
数据结构·数据库·redis
IvanCodes2 小时前
六、Docker 核心技术:Dockerfile 指令详解
java·数据库·docker
寻星探路2 小时前
数据结构造神计划第三天---数据类型
数据库
YUELEI1182 小时前
langchain 缓存 Caching
缓存·langchain
孤独的人2 小时前
WordPress 性能优化:从插件到 CDN 的全方位缓存设置指南
spring·缓存·性能优化
l5657583 小时前
第五十五天(SQL注入&增删改查&HTTP头&UA&XFF&Referer&Cookie&无回显报错&复盘)
数据库