技术工具类:通过Redis的自增序列来生成系统使用的序列号

8 篇文章 0 订阅
1 篇文章 0 订阅

直接上代码:

package com.fuli.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;

/**
 * @description: 通过Redis生成序列号
 * @author: YqZhilan
 * @date: 2020-08-01
 */
@Component
public class RedisSequenceUtil {

    @Autowired
    private RedisUtil redisUtil;

    private final long delta = 1; // 默认步长

    /***
     * 生成序列值的前半段
     * @param strs
     * @return
     */
    public String generateSequenceF(String... strs) {
        StringBuilder sb = new StringBuilder();
        if (strs != null) {
            for (int i = 0; i < strs.length; i++) {
                sb.append(strs[i]);
            }
        }
        return sb.toString();
    }

    /***
     * 获取下一个序列号
     * @param key Redis Key值
     * @param value 初始值
     * @param timeout 过期时间
     * @return
     */
    public String setSequence(String key, long value, long timeout) {

        redisUtil.set(key, value, timeout);
        return value+"";
    }

    /***
     * 获取当前序列号
     * @param key Redis Key值
     * @return
     */
    public String getCurrentSequence(String key) {
        Object obj = redisUtil.get(key);
        return obj == null ? "" : obj.toString();
    }

    /***
     * 获取下一个序列号
     * @param key Redis Key值
     * @return
     */
    public String getNextSequence(String key) {

        return this.getNextSequence(key, this.delta);
    }

    /***
     * 获取下一个序列号
     * @param key Redis Key值
     * @param delta 增长步长
     * @return
     */
    public String getNextSequence(String key, long delta) {

        redisUtil.incr(key, delta);
        Object obj = redisUtil.get(key);
        return obj == null ? "" : obj.toString();
    }

    /***
     * 获取本天剩余的秒数
     * @return
     */
    public long getLeftSeconsOfDay() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return (cal.getTimeInMillis() - System.currentTimeMillis()) / 1000;
    }

}

说明:

private RedisUtil redisUtil; 该类仅是一个Redis操作的工具类,可以自己封装。

至此结束 ... ...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值