@@ -20,11 +20,16 @@ import (
2020 log "code.google.com/p/log4go"
2121 "errors"
2222 "fmt"
23+ myrpc "github.com/Terry-Mao/gosnowflake/rpc"
2324 "net"
2425 "net/rpc"
2526 "time"
2627)
2728
29+ const (
30+ maxNextIdsNum = 100
31+ )
32+
2833type SnowflakeRPC struct {
2934 idWorkers []* IdWorker
3035}
@@ -41,7 +46,7 @@ func InitRPC() error {
4146 log .Error ("init workerId: %d already exists" , workerId )
4247 return fmt .Errorf ("init workerId: %d exists" , workerId )
4348 }
44- idWorker , err := NewIdWorker (workerId , MyConf .DatacenterId )
49+ idWorker , err := NewIdWorker (workerId , MyConf .DatacenterId , MyConf . Twepoch )
4550 if err != nil {
4651 log .Error ("NewIdWorker(%d, %d) error(%v)" , MyConf .DatacenterId , workerId )
4752 return err
@@ -98,6 +103,37 @@ func (s *SnowflakeRPC) NextId(workerId int64, id *int64) error {
98103 return nil
99104}
100105
106+ // NextIds generate specified num ids.
107+ func (s * SnowflakeRPC ) NextIds (args * myrpc.NextIdsArgs , ids * []int64 ) error {
108+ if args == nil {
109+ return errors .New ("args is nil" )
110+ }
111+ if args .WorkerId > maxWorkerId || args .WorkerId < 0 {
112+ log .Error ("worker Id can't be greater than %d or less than 0" , maxWorkerId )
113+ return errors .New (fmt .Sprintf ("worker Id: %d error" , args .WorkerId ))
114+ }
115+ if args .Num > maxNextIdsNum || args .Num < 0 {
116+ log .Error ("num can't be greater than %d or less than 0" , maxNextIdsNum )
117+ return errors .New (fmt .Sprintf ("num: %d error" , args .Num ))
118+ }
119+ if worker := s .idWorkers [args .WorkerId ]; worker == nil {
120+ log .Warn ("workerId: %d not register" , args .WorkerId )
121+ return fmt .Errorf ("snowflake workerId: %d don't register in this service" , args .WorkerId )
122+ } else {
123+ tids := make ([]int64 , args .Num )
124+ for i := 0 ; i < args .Num ; i ++ {
125+ if tid , err := worker .NextId (); err != nil {
126+ log .Error ("worker.NextId() error(%v)" , err )
127+ return err
128+ } else {
129+ tids [i ] = tid
130+ }
131+ }
132+ * ids = tids
133+ }
134+ return nil
135+ }
136+
101137// DatacenterId return the services's datacenterId.
102138func (s * SnowflakeRPC ) DatacenterId (ignore int , dataCenterId * int64 ) error {
103139 * dataCenterId = MyConf .DatacenterId
0 commit comments