• redis生成唯一流水id,自增


    1. package com.csgholding.pvgpsp.ums.controller;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.data.redis.core.RedisTemplate;
    4. import org.springframework.data.redis.support.atomic.RedisAtomicLong;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. import java.time.LocalDate;
    8. @RestController
    9. public class CodeController {
    10. @Autowired
    11. private RedisTemplate redisTemplate;
    12. /**
    13. * 15 18位 前缀=当前日期=2018112921303030-5位自增id(高并发请下 先天性安全) 00001
    14. * 00010
    15. * 00100
    16. * 01000
    17. * 11000
    18. * 在相同毫秒情况下,最多只能生成10万-1=99999订单号
    19. * 假设:双11每毫秒99万笔
    20. * 提前生成号订单号码存放在redis中
    21. *

    22. * 9.9万*1000=900万
    23. * 考虑失效时间问题 24小时
    24. *
    25. * @return
    26. */
    27. // 基于Redis 实现分布式全局id
    28. @RequestMapping("/getCode")
    29. public String order(String key, String name) {
    30. RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
    31. long incrementAndGet = redisAtomicLong.incrementAndGet();
    32. // 6位
    33. String orderId = name + prefix() + String.format("%1$06d", incrementAndGet);
    34. return orderId;
    35. }
    36. //自增+sum个,暂时不要
    37. // @RequestMapping("/addCodeSum")
    38. // public String order1(String key,Integer sum) {
    39. // RedisAtomicLong redisAtomicLong = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
    40. // // // 起始值
    41. // // redisAtomicLong.set(10);
    42. // // 设置步长加10
    43. // redisAtomicLong.addAndGet(sum);
    44. // return redisAtomicLong.incrementAndGet() + "";
    45. // }
    46. /**
    47. * @return 日期
    48. */
    49. public static String prefix() {
    50. String[] split = LocalDate.now().toString().split("-");
    51. String time = "";
    52. for (String s : split) {
    53. time += s;
    54. }
    55. return time;
    56. }
    57. }

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

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

  • 相关阅读:
    贪心算法 —— 字典序删除字符
    【PyQt学习篇 · ③】:QObject - 神奇的对象管理工具
    Debian10Standard无网络安装后,设置静态IP,安装openssh-server 221024记录
    微服务框架:一招实现降本、提质、增效办公!
    应急响应笔记
    课程设计-天天象棋作弊软件判别
    Feign负载均衡写法
    java毕业设计毕业生就业去向登记管理系统mybatis+源码+调试部署+系统+数据库+lw
    「Verilog学习笔记」移位运算与乘法
    YOLO系列目标检测算法-YOLOv6
  • 原文地址:https://blog.csdn.net/qx020814/article/details/134536860