Пример #1
0
func TestDuplicateKeys(t *testing.T) {
	worker, err := idworker.NewIdWorker(1, 1)
	assert.Nil(t, err)

	const MAXIDS = 100000

	var ids [MAXIDS]uint64

	start := time.Now()

	for i := 0; i < MAXIDS; i++ {
		id, err := worker.Next()
		assert.Nil(t, err)

		ids[i] = id
	}

	for i := 1; i < MAXIDS; i++ {
		if ids[i-1] > ids[i] {
			t.Errorf("next id %v is smaller then previous one %v", ids[i], ids[i-1])
		}
	}

	end := time.Now()

	delta := float64(end.UnixNano()-start.UnixNano()) / float64(1000*1000)
	t.Logf("Execution time: %fms\n", delta)
	t.Logf("Ids/sec: %f\n", float64(MAXIDS)/delta)
}
Пример #2
0
func runHTTPServer(host string, port int, workerId uint64, datacenterId uint64) {
	worker, err := idworker.NewIdWorker(workerId, datacenterId)

	if err == nil {
		http.HandleFunc("/api/snowflake", func(w http.ResponseWriter, r *http.Request) {
			snowflakeHandler(w, r, worker)
		})

		http.ListenAndServe(fmt.Sprintf("%s:%d", host, port), nil)
	} else {
		log.Fatal(err)
	}
}
Пример #3
0
func TestNewIdWorker(t *testing.T) {
	worker, err := idworker.NewIdWorker(1, 1)
	assert.Nil(t, err)

	id1, err := worker.Next()
	assert.Nil(t, err)

	id2, err := worker.Next()
	assert.Nil(t, err)

	if id1 > id2 {
		t.Errorf("id2 %v is smaller then previous one %v", id2, id1)
	}
}
Пример #4
0
func BenchmarkIdWorker(b *testing.B) {
	worker, err := idworker.NewIdWorker(1, 1)
	if err == nil {
		b.ResetTimer()
		for i := 0; i < b.N; i++ {
			id, err := worker.Next()
			if err == nil {
				fmt.Sprintf("%d", id)
			} else {
				b.Errorf("Failed to create id")
			}
		}
	} else {
		b.Errorf("Failed to create IdWorker")
	}
}
Пример #5
0
func runThriftServer(host string, port int, protocol string, framed bool, buffered bool, workerId uint64, datacenterId uint64) {
	var protocolFactory thrift.TProtocolFactory
	switch protocol {
	case "compact":
		protocolFactory = thrift.NewTCompactProtocolFactory()
	case "simplejson":
		protocolFactory = thrift.NewTSimpleJSONProtocolFactory()
	case "json":
		protocolFactory = thrift.NewTJSONProtocolFactory()
	case "binary", "":
		protocolFactory = thrift.NewTBinaryProtocolFactoryDefault()
	default:
		fmt.Fprint(os.Stderr, "Invalid protocol specified", protocol, "\n")
		Usage()
		os.Exit(1)
	}

	var transportFactory thrift.TTransportFactory
	if buffered {
		transportFactory = thrift.NewTBufferedTransportFactory(8192)
	} else {
		transportFactory = thrift.NewTTransportFactory()
	}

	if framed {
		transportFactory = thrift.NewTFramedTransportFactory(transportFactory)
	}

	var err error
	var transport thrift.TServerTransport
	transport, err = thrift.NewTServerSocket(fmt.Sprintf("%s:%d", host, port))
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	worker, err := idworker.NewIdWorker(workerId, datacenterId)

	processor := snowflake.NewSnowflakeProcessor(worker)

	if err == nil {
		server := thrift.NewTSimpleServer4(processor, transport, transportFactory, protocolFactory)
		server.Serve()
	} else {
		log.Fatal(err)
	}
}