如何用redis來生成唯一Id

2021-09-22 19:35:29 字數 4747 閱讀 3234

那麼,就讓樓主來介紹一下redisatomiclong類吧~

redisatomiclong類的構造方法如下:

該例項對應的自動增長的主鍵的key的名字為為rediscounter,如果redis中存在key的name為rediscounter的鍵值對,那麼,則取其值;否則,將rediscounter對應的key值設定為0;

建立乙個新的redisatomiclong例項,該例項對應的自動增長的主鍵的key的名字為為rediscounter,並將key name為rediscounter的值設定為initialvalue;

redisatomiclong類有以下幾個主要的方法:

那麼,我們如何獲得乙個redisatomiclong例項呢?樓主提供以下兩個方法:

? 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

p:host-name="$"p:port="$"p:password="$"p:pool-config-ref="jedispoolconfig"/>

class="org.springframework.data.redis.serializer.stringredisserializer"/>

方法一:直接在配置檔案中配置

? 1

2

3

4

5

在需要用到redisatomiclong例項的類裡面加入下面這段**即可

? 1

2

@resource

privateredisatomiclong redisatomiclong;

方法二:在**中直接獲得

? 1

redisatomiclong redisatomiclong =newredisatomiclong("somekey",redistemplate.getconnectionfactory());

好了,獲得redisatomiclong例項之後如何來獲得自動增長的值呢?

? 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

// 第一次,設定初始值

longoriginal = 0l;

// 獲取 code 值

original = redisatomiclong.get();

system.out.println("*****************original:"+original);

// 第一次,設定初始值

if(original == 0l)

//獲得加1後的值

longnow = redisatomiclong.incrementandget();

system.out.println("*****************now:"+now);

輸出值:

*****************original:0

*****************now:6

有人或許會問,如果我想要同時有兩個自增長的主鍵怎麼辦?下面的這段**就可以解決這個問題~

? 1

2

3

4

5

6

7

8

9

10

11

12

13

14

redisatomiclong atomiclong1 =newredisatomiclong("somekey1", redistemplate.getconnectionfactory(),3l);//建立例項的時候就設定初始值為3

redisatomiclong atomiclong2 =newredisatomiclong("somekey2", redistemplate.getconnectionfactory(),5l);//建立例項的時候就設定初始值為5

longnow1 = atomiclong1.incrementandget();

longnow2 = atomiclong2.incrementandget();

system.out.println("*****************now:"+now1);

system.out.println("*****************now:"+now2);

輸出值:

*****************now:6

*****************now:7

出處:

如何用redis來生成唯一Id

那麼,就讓樓主來介紹一下redisatomiclong類吧 redisatomiclong類的構造方法如下 該例項對應的自動增長的主鍵的key的名字為為rediscounter,如果redis中存在key的name為rediscounter的鍵值對,那麼,則取其值 否則,將rediscounter對...

如何用word vb巨集來生成sql

昨天boss下了個命令讓我用word巨集的方式來快速生成sql,這樣在我們建表的時候就不用在一條一條元資料的輸入。從而提高效率節約成本 接到命令後就開始著手來做,一邊上網搜相關的現成的材料,一邊看vb巨集的 教程。終於讓我寫出了這個程式,雖說有點兒小吧,可是感覺挺好的。這裡的vb巨集要針對固定的資料...

使用redis生成全域性唯一id

生成唯一客戶編碼 需求 1.id生成有一定規則,可識別 2.全域性保持唯一,支援分布式 思路 1.年月日 每日自增數 2.每天23 59 59秒把自增數清0 優勢 1.通過年月日可以看出使用者註冊時間 2.通過自增數可以看出每日註冊量 使用redis原因 redis本身單執行緒,不會出現併發問題 r...