在之前的项目中需要用到一个自动增长的主键,该主键需要包含字母,所以没有办法用到数据库的自增主键。楼主要高手的指导下,发现Redis的RedisAtomicLong类可以解决这个麻烦。而且redis为单线程,不存在线程安全问题

那么,就让楼主来介绍一下RedisAtomicLong类吧~

RedisAtomicLong类的构造方法如下:

  • 构造方法一:

    public RedisAtomicLong(java.lang.String redisCounter,
    RedisConnectionFactory factory)

      

该实例对应的自动增长的主键的key的名字为为redisCounter,如果redis中存在key的name为redisCounter的键值对,那么,则取其值;否则,将redisCounter对应的key值设置为0;

  • 构造方法二:

    public RedisAtomicLong(java.lang.String redisCounter,
    RedisConnectionFactory factory,
    long initialValue)  

创建一个新的RedisAtomicLong实例,该实例对应的自动增长的主键的key的名字为为redisCounter,并将key name为redisCounter的值设置为initialValue;

RedisAtomicLong类有以下几个主要的方法:

  • 方法一:

    public long get();//返回当前的值
    

      

  • 方法二:

    public void set(long newValue);//设置当前实例的值为newValue
    

      

  • 方法三:

    public long incrementAndGet();//将当前实例的key值加一并且返回
    

      

那么,我们如何获得一个RedisAtomicLong实例呢?楼主提供以下两个方法:

在获取实例之前,我们需要设置好jedis的配置。 
在application.xml文件中,加入以下配置:

<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.pool.maxTotal}" />
<property name="maxIdle" value="${redis.pool.maxIdle}" />
<property name="testOnBorrow" value="${redis.pool.testOnBorrow}" />
</bean> <!-- jedis服务器配置 -->
<bean id="jedisShardInfo" class="redis.clients.jedis.JedisShardInfo">
<constructor-arg index="0" value="${redis.ip}" />
<constructor-arg index="1" value="${redis.port}" type="int" />
</bean> <bean id="jedisConnFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
p:host-name="${redis.ip}" p:port="${redis.port}" p:password="${redis.pass}" p:pool-config-ref="jedisPoolConfig"/> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="jedisConnFactory"/>
<property name="keySerializer" ref="keySerializer"/>
<property name="enableTransactionSupport" value="false"/>
</bean> <!-- redis 序列化-->
<bean id="keySerializer"
class="org.springframework.data.redis.serializer.StringRedisSerializer" />

  

方法一:直接在配置文件中配置

<!-- someKey为设置的自增长主键的key的名字-->
<bean id="redisAtomicLong" class="org.springframework.data.redis.support.atomic.RedisAtomicLong">
<constructor-arg name="redisCounter" value="someKey"></constructor-arg>
<constructor-arg name="factory" ref="jedisConnFactory"></constructor-arg>
</bean> 

在需要用到redisAtomicLong实例的类里面加入下面这段代码即可

@Resource
private RedisAtomicLong redisAtomicLong;

  

方法二:在代码中直接获得

RedisAtomicLong redisAtomicLong = new RedisAtomicLong("someKey",redisTemplate.getConnectionFactory());

  

好了,获得redisAtomicLong实例之后如何来获得自动增长的值呢?

// 第一次,设置初始值
long original = 0L; // 获取 code 值
original = redisAtomicLong.get();
System.out.println("*****************original:"+original); // 第一次,设置初始值
if (original == 0L) {
redisAtomicLong.set(5L);
}
//获得加1后的值
long now = redisAtomicLong.incrementAndGet();
System.out.println("*****************now:"+now); 输出值:
*****************original:0
*****************now:6

  

有人或许会问,如果我想要同时有两个自增长的主键怎么办?下面的这段代码就可以解决这个问题~

RedisAtomicLong atomicLong1 = new RedisAtomicLong("somekey1", redisTemplate.getConnectionFactory(),3L);//创建实例的时候就设置初始值为3
RedisAtomicLong atomicLong2 = new RedisAtomicLong("somekey2", redisTemplate.getConnectionFactory(),5L);//创建实例的时候就设置初始值为5 long now1 = atomicLong1.incrementAndGet();
long now2 = atomicLong2.incrementAndGet(); System.out.println("*****************now:"+now1);
System.out.println("*****************now:"+now2); 输出值:
*****************now:6
*****************now:7

  

如何用redis来生成唯一Id的更多相关文章

  1. php 生成唯一id的几种解决方法

    php 生成唯一id的几种解决方法   网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid ...

  2. PHP使用SnowFlake算法生成唯一ID

    前言:最近需要做一套CMS系统,由于功能比较单一,而且要求灵活,所以放弃了WP这样的成熟系统,自己做一套相对简单一点的.文章的详情页URL想要做成url伪静态的格式即xxx.html 其中xxx考虑过 ...

  3. php生成唯一id/唯一标识符/唯一订单号

    /** * php 生成唯一id * https://blog.csdn.net/hzqghost/article/details/18914681 */ function guid($factor= ...

  4. 如何使用php生成唯一ID的4种方法

    php生成唯一ID的应用场景非常普遍,如临时缓存文件名称,临时变量,临时安全码等,uniqid()函数基于以微秒计的当前时间,生成一个唯一的 ID.由于生成唯一ID与微秒时间关联,因此ID的唯一性非常 ...

  5. PHP获取时间戳和微秒数以及生成唯一ID

    microtime函数 描述:返回当前Unix时间戳和微秒数 语法:mixed microtime( [ bool $get_as_float ] ) //直接输出 echo microtime(); ...

  6. 根据twitter的snowflake算法生成唯一ID

    C#版本 /// <summary> /// 根据twitter的snowflake算法生成唯一ID /// snowflake算法 64 位 /// 0---0000000000 000 ...

  7. C# 根据twitter的snowflake算法生成唯一ID

    C# 版算法: using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...

  8. php 生成唯一id的几种解决方法(实例)

    php 生成唯一id,网上查了下,有很多的方法 1.md5(time() . mt_rand(1,1000000)); 这种方法有一定的概率会出现重复 2.php内置函数uniqid() uniqid ...

  9. python学习之-- 生成唯一ID

    以下以2种方法生成唯一ID def uuid_method(): """第一种方法""" import uuid return str(uu ...

随机推荐

  1. js操作时间 加法 减法 计算 格式化时间

    Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月份 "d ...

  2. java之TCP(Socket,serverSocket)实例

    import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import ...

  3. c语言中数组名和指针变量的区别

    编译器工作原理:在64位的计算机中,当创建一个指针变量时,计算机会为它分配8个字节的存储空间.但如果创建的是数组呢?计算机会为数组分配存储空间,但不会为数组变量分配任何空间,编译器仅在出现它的地方把它 ...

  4. Atitit.  Exception in thread "main" java.lang.Error: Unresolved compilation problem:

    Atitit.  Exception in thread "main" java.lang.Error: Unresolved compilation problem: 1.1. ...

  5. 413. Reverse Integer【easy】

    Reverse digits of an integer. Returns 0 when the reversed integer overflows (signed 32-bit integer). ...

  6. 如何使用ip端口来浏览自己的网站

    现在做网站的朋友越来越多,域名注册后往往需要进行备案,而在备案期间我们的域名又不能正常打开,在服务器上直接编辑浏览我们的网站有些棘手,思来想去,在我们购买的服务器ip后面加上个端口来达到域名一样的效果 ...

  7. html 基本标签 ---短语

    <em> </em> 着重 <strong> </strong> 强调 <dfn> </dfn> 定义 <code> ...

  8. ECC加密算法原理入门介绍

    前言 同RSA(Ron Rivest,Adi Shamir,Len Adleman三位天才的名字)一样,ECC(Elliptic Curves Cryptography,椭圆曲线密码编码学)也属于公开 ...

  9. Sqlserver 批量数据更改

    insert into AAA select GETDATE(),name from BBB where aid=0 update a set a = b.a,b=b.b,c=b.c from t a ...

  10. java性能监控工具:jmap命令详解

    .命令基本概述 Jmap是一个可以输出所有内存中对象的工具,甚至可以将VM 中的heap,以二进制输出成文本.打印出某个java进程(使用pid)内存内的,所有‘对象’的情况(如:产生那些对象,及其数 ...