【redis】使用redis RedisAtomicLong生成自增的ID值

本文介绍了在Spring环境中,如何利用RedisAtomicLong通过RedisTemplate创建自增ID。详细讲述了RedisSequenceFactory类的封装,RedisTemplate的配置以及具体的使用测试案例,其中ID以“hello”为键,并设置在每天23:59:59:999自动过期并重置为0。
Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

本文介绍在spring+redis组合时,使用redis的RedisAtomicLong生成自增的ID值。

1、自增ID生成类

RedisSequenceFactory是一个简单封装类,用于使用redisTemplate生成自增ID值。代码如下:

package cn.landsem.cache.redis;

import java.io.Serializable;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;

public class RedisSequenceFactory {
	@Autowired
	RedisTemplate<String, Serializable> mRedisTemp;
	
	/** 
	* @Title: set 
	* @Description: set cache.
	* @param key
	* @param value
	* @param expireTime      
	*/  
	public void set(String key,int value,Date expireTime) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		counter.set(value);
		counter.expireAt(expireTime);		
	}
	
	/** 
	* @Title: set 
	* @Description: set cache.
	* @param key
	* @param value
	* @param timeout
	* @param unit      
	*/  
	public void set(String key,int value,long timeout,TimeUnit unit) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		counter.set(value);
		counter.expire(timeout, unit);
	}
	
	/** 
	* @Title: generate 
	* @Description: Atomically increments by one the current value.
	* @param key
	* @return      
	*/  
	public long generate(String key) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		return counter.incrementAndGet();
	}	
	
	/** 
	* @Title: generate 
	* @Description: Atomically increments by one the current value.
	* @param key
	* @return      
	*/  
	public long generate(String key,Date expireTime) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		counter.expireAt(expireTime);
		return counter.incrementAndGet();	      
	}		
	
	/** 
	* @Title: generate 
	* @Description: Atomically adds the given value to the current value.
	* @param key
	* @param increment
	* @return      
	*/  
	public long generate(String key,int increment) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		return counter.addAndGet(increment);		      
	}
	
	/** 
	* @Title: generate 
	* @Description: Atomically adds the given value to the current value.
	* @param key
	* @param increment
	* @param expireTime
	* @return      
	*/  
	public long generate(String key,int increment,Date expireTime) {
		RedisAtomicLong counter = new RedisAtomicLong(key, mRedisTemp.getConnectionFactory());
		counter.expireAt(expireTime);
		return counter.addAndGet(increment);		      
	}	
}

2、RedisTemplate配置

RedisTemplate在基于java的配置类中进行配置,主要代码如下:

	/**
	 * @Title: getDefaultRedisTemplate
	 * @Description: Get a default redis cache template.
	 * @return
	 */
	@Bean
	public RedisTemplate<String, Serializable> getDefaultRedisTemplate(
			RedisConnectionFactory cf,RedisSerializer<?> rs) {
		RedisTemplate<String, Serializable> redisTemplate = new RedisTemplate<String, Serializable>();
		redisTemplate.setConnectionFactory(cf);
		redisTemplate.setDefaultSerializer(rs);//Use jboss serialization
		redisTemplate.setKeySerializer(new StringRedisSerializer());//Use String serialization.		
		return redisTemplate;
	}	

3、使用测试

如下为生成一个自增ID,该自增ID缓存的key为“hello”,并且该缓存在当天23:59:59:999时会自动过期,过期后会重置为0。主要的源代码如下:

    /** 
    * @Title: getTodayEndTime 
    * @Description: Get the cache expire time.
    * @return      
    */  
    private static Date getTodayEndTime() {  
        Calendar todayEnd = Calendar.getInstance();  
        todayEnd.set(Calendar.HOUR_OF_DAY, 23);  
        todayEnd.set(Calendar.MINUTE, 59);  
        todayEnd.set(Calendar.SECOND, 59);  
        todayEnd.set(Calendar.MILLISECOND, 999);  
        return todayEnd.getTime();  
    } 

  /**
  * The message sequence key.
  */
  public static final String sMsgSequenceKeyFormat = "hello";

  @Autowired
  private RedisSequenceFactory mRedisSequenceFactory; 

   public void test()  {
      long v = mRedisSequenceFactory.generate(sMsgSequenceKeyFormat,getTodayEndTime())
   }


您可能感兴趣的与本文相关的镜像

Llama Factory

Llama Factory

模型微调
LLama-Factory

LLaMA Factory 是一个简单易用且高效的大型语言模型(Large Language Model)训练与微调平台。通过 LLaMA Factory,可以在无需编写任何代码的前提下,在本地完成上百种预训练模型的微调

Java 使用 Redis 实现自流水号有多种方法,以下为你介绍几种常见的实现方式: ### 利用 RedisAtomicLong 类按天生成流水号 可以利用 RedisRedisAtomicLong 类实现每天生成流水号的功能,将其每天第一次放置一个新的自(一天过期),然后和每天的日期相加即可。例如生成格式为 20190701 + 001 的流水号,当天后续生成 20190701 + 002 等,要多少个 0 可以自己配置。示例代码如下: ```java import org.springframework.data.redis.support.atomic.RedisAtomicLong; import java.text.SimpleDateFormat; import java.util.Date; public class DailySerialNumberGenerator { private RedisAtomicLong redisAtomicLong; public DailySerialNumberGenerator(String key, String redisHost, int redisPort) { // 配置 Redis 连接等,此处省略部分代码 redisAtomicLong = new RedisAtomicLong(key, redisConnectionFactory); } public String generateSerialNumber() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); String dateStr = sdf.format(new Date()); long increment = redisAtomicLong.incrementAndGet(); // 设置过期时间为一天 if (increment == 1) { redisAtomicLong.expire(1, java.util.concurrent.TimeUnit.DAYS); } String serialNumber = String.format("%03d", increment); return dateStr + serialNumber; } } ``` ### 使用 Redis 事务确保序列号生成的原子性 使用 Redis 事务确保序列号生成的原子性,首次生成时会从数据库获取当前最大。示例代码如下: ```java import org.springframework.data.redis.core.RedisTemplate; import java.util.function.Function; public class SerialNumberGenerator { private RedisTemplate<String, Long> redisTemplate; public SerialNumberGenerator(RedisTemplate<String, Long> redisTemplate) { this.redisTemplate = redisTemplate; } private Long generateSerialByRedis(String prefix, String year, Function<String, Long> getMaxDbValueFunc) { String key = prefix + year; if (!redisTemplate.hasKey(key)) { Long maxDbValue = getMaxDbValueFunc.apply(key); redisTemplate.opsForValue().set(key, maxDbValue + 1); } else { return redisTemplate.opsForValue().increment(key); } return redisTemplate.opsForValue().get(key); } } ``` ### 按年流水号并发自 可以承受并发的按年流水号并发自实现,示例代码如下: ```java import org.springframework.data.redis.core.StringRedisTemplate; import java.util.Calendar; public class YearlySerialNumberGenerator { private StringRedisTemplate stringRedisTemplate; public YearlySerialNumberGenerator(StringRedisTemplate stringRedisTemplate) { this.stringRedisTemplate = stringRedisTemplate; } public synchronized String autoApplyId() throws Exception { int currentYear = Calendar.getInstance().get(Calendar.YEAR); // redis 的 key String applyIdKey = "apply_id_number"; // redis 的 value 模板,例 2022000001 String applyIdNumber = String.format(currentYear + "%06d", 1); // 如果存在 key 则在原有 value 序号上自 +1,如到新的一年则更新 value 为 新年份 + 000001 if (stringRedisTemplate.hasKey(applyIdKey)) { String yearNumber = stringRedisTemplate.opsForValue().get(applyIdKey).substring(0, 4); int dataYear = Integer.parseInt(yearNumber); if (dataYear != currentYear) { stringRedisTemplate.opsForValue().set(applyIdKey, applyIdNumber); } else { stringRedisTemplate.opsForValue().increment(applyIdKey, 1); } } else { // 如果不存在 key 则直接设置 value 为 当前年份 + 000001 stringRedisTemplate.opsForValue().set(applyIdKey, applyIdNumber); } String yearNumber = stringRedisTemplate.opsForValue().get(applyIdKey); String applyId = "A" + yearNumber; return applyId; } } ```
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值