for issue #10; an IdGenerator interface, use bson.ObjectId as default

This commit is contained in:
mikespook 2013-02-28 13:28:48 +08:00
parent faa0ca07ee
commit 7a8a5d4a6a
3 changed files with 50 additions and 21 deletions

View File

@ -12,16 +12,15 @@ import (
"time" "time"
"bytes" "bytes"
"strconv" "strconv"
"github.com/mikespook/golib/autoinc"
"github.com/mikespook/gearman-go/common" "github.com/mikespook/gearman-go/common"
) )
var ( var (
ai *autoinc.AutoInc IdGen IdGenerator
) )
func init() { func init() {
ai = autoinc.New(0, 1) IdGen = NewObjectId()
} }
// Status handler // Status handler
@ -316,7 +315,7 @@ flag byte, jobhandler JobHandler) (handle string) {
default: default:
datatype = common.SUBMIT_JOB datatype = common.SUBMIT_JOB
} }
id := strconv.Itoa(int(ai.Id())) id := IdGen.Id()
handle = client.do(funcname, data, datatype, id) handle = client.do(funcname, data, datatype, id)
if jobhandler != nil { if jobhandler != nil {
client.jobhandlers[id] = jobhandler client.jobhandlers[id] = jobhandler

37
client/id.go Normal file
View File

@ -0,0 +1,37 @@
package client
import (
"strconv"
"labix.org/v2/mgo/bson"
"github.com/mikespook/golib/autoinc"
)
type IdGenerator interface {
Id() string
}
// ObjectId
type objectId struct {
bson.ObjectId
}
func (id *objectId) Id() string {
return id.String()
}
func NewObjectId() IdGenerator {
return &objectId{bson.NewObjectId()}
}
// AutoIncId
type autoincId struct {
*autoinc.AutoInc
}
func (id *autoincId) Id() string {
return strconv.Itoa(id.AutoInc.Id())
}
func NewAutoIncId() IdGenerator {
return &autoincId{autoinc.New(1, 1)}
}

View File

@ -8,39 +8,32 @@ import (
func main() { func main() {
var wg sync.WaitGroup var wg sync.WaitGroup
// Set the autoinc id generator
// You can write your own id generator
// by implementing IdGenerator interface.
client.IdGen = client.NewAutoIncId()
c, err := client.New("127.0.0.1:4730") c, err := client.New("127.0.0.1:4730")
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
defer c.Close() defer c.Close()
echo := []byte("Hello\x00 world")
c.JobHandler = func(job *client.Job) error {
log.Printf("%s", job.Data)
wg.Done()
return nil
}
c.ErrHandler = func(e error) { c.ErrHandler = func(e error) {
log.Println(e) log.Println(e)
panic(e) panic(e)
} }
echo := []byte("Hello\x00 world")
wg.Add(1) wg.Add(1)
c.Echo(echo) c.Echo(echo)
wg.Add(1) wg.Add(1)
handle, err := c.Do("ToUpper", echo, client.JOB_NORMAL) jobHandler := func(job *client.Job) {
if err != nil { log.Printf("%s", job.Data)
log.Fatalln(err)
} else {
log.Println(handle)
}
c.StatusHandler = func(handle string, known, running bool, numerator, denominator uint64) {
log.Printf("%s: %b, %b, %d, %d", handle, known, running, numerator, denominator)
wg.Done() wg.Done()
} }
handle := c.Do("ToUpper", echo, client.JOB_NORMAL, jobHandler)
wg.Add(1) wg.Add(1)
c.Status(handle) log.Printf("%t", c.Status(handle))
wg.Wait() wg.Wait()
} }