本文整理汇总了Golang中github.com/aerospike/aerospike-client-go.NewKey函数的典型用法代码示例。如果您正苦于以下问题:Golang NewKey函数的具体用法?Golang NewKey怎么用?Golang NewKey使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewKey函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: send
func send(cache []Event) {
fmt.Println("sending %s", len(cache))
for index, element := range cache {
_ = index
//fmt.Println(element.id, element.event, element.value)
//fmt.Println(index)
key, _ := as.NewKey("test", "totals", "total_votes")
ops := []*as.Operation{
as.AddOp(as.NewBin("total_votes", 1)), // add the value of the bin to the existing value
as.GetOp(), // get the value of the record after all operations are executed
}
_, _ = client.Operate(nil, key, ops...)
key, _ = as.NewKey("test", "totals", element.value)
ops = []*as.Operation{
as.AddOp(as.NewBin(element.value, 1)), // add the value of the bin to the existing value
as.GetOp(), // get the value of the record after all operations are executed
}
_, _ = client.Operate(nil, key, ops...)
//panicOnError(err)
//fmt.Println(rec)
// client.Set(element.id, element.value)
// client.Get(element.id)
// client.Incr("total_votes")
// client.Incr(element.value)
}
}
示例2: CloseAuction
// When the auction has completed, perform the following logic.
func CloseAuction(offerId int, bid *m.Bid) {
auctionMap.Remove(offerId)
// Check if the broker has enough inventory
offerKeyId := fmt.Sprintf("%s:%d", OFFERS, offerId)
offerKey, _ := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
offerRec, _ := db.Get(readPolicy, offerKey)
sellerId := offerRec.Bins["broker_id"].(int)
// add to buyer's inventory and reduce credit
buyerKeyId := fmt.Sprintf("%s:%d", BROKERS, bid.BrokerId)
buyerKey, _ := as.NewKey(NAMESPACE, BROKERS, buyerKeyId)
db.Operate(writePolicy, buyerKey,
as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), offerRec.Bins["quantity"].(int))),
as.AddOp(as.NewBin("credit", -1*offerRec.Bins["quantity"].(int)*int(bid.Price))),
)
// reduce seller's inventory and add to credit
sellerKeyId := fmt.Sprintf("%s:%d", BROKERS, sellerId)
sellerKey, _ := as.NewKey(NAMESPACE, BROKERS, sellerKeyId)
db.Operate(writePolicy, sellerKey,
as.AddOp(as.NewBin(offerRec.Bins["ticker"].(string), -1*offerRec.Bins["quantity"].(int))),
as.AddOp(as.NewBin("credit", offerRec.Bins["quantity"].(int)*int(bid.Price))),
)
// mark the bid as winner
bidKeyId := fmt.Sprintf("%s:%d", BIDS, bid.Id)
bidKey, _ := as.NewKey(NAMESPACE, BIDS, bidKeyId)
db.Put(writePolicy, bidKey, as.BinMap{"winner": 1})
db.Put(writePolicy, offerKey, as.BinMap{"finished": 1, "winner": bid.Id})
}
示例3: Bid
// Place a Bid on an offer for sale
func (command *Command) Bid(r *http.Request, bid *m.Bid, bidId *int) error {
var err error
offerKeyId := fmt.Sprintf("%s:%d", OFFERS, bid.OfferId)
offerKey, err := as.NewKey(NAMESPACE, OFFERS, offerKeyId)
if err != nil {
return err
}
offerRec, err := db.Get(readPolicy, offerKey)
if err != nil {
return err
}
bidChan := auctionMap.Get(bid.OfferId)
if err != nil || offerRec == nil || bidChan == nil {
return errors.New("Auction has finished.")
}
// bid.Id = int(atomic.AddInt64(&bidIdSeq, 1))
bid.Id, err = nextSeq("bid")
if err != nil {
return nil
}
bidKeyId := fmt.Sprintf("%s:%d", BIDS, bid.Id)
bidKey, err := as.NewKey(NAMESPACE, BIDS, bidKeyId)
if err != nil {
return err
}
bidBins := as.BinMap{
"bid_id": bid.Id,
"auction_id": bid.OfferId,
"broker_id": bid.BrokerId,
"price": bid.Price,
}
if err := db.Put(writePolicy, bidKey, bidBins); err != nil {
return err
}
*bidId = bid.Id
// bids < asking price will not be considered in the auction
// however, we also prevent the bidder from submitting a new
// bid (ie 1 bid per bidder rule)
if offerRec.Bins["price"].(int) < bid.Price {
bidChan <- bid
broadcast <- &m.Notification{
Version: "2.0",
Method: "Bid",
Params: *bid,
}
}
return nil
}
示例4: voteHandler
func voteHandler(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
w.Header().Set("Content-Type", "text/plain")
e := Event{id: r.FormValue("u"), event: "vote", value: r.FormValue("v")}
//fmt.Println(i)
i = i + 1
e.id = strconv.Itoa(i)
key, err := as.NewKey("test", "votes", e.id)
bins := as.BinMap{
"v": e.value,
}
err = client.Put(writePolicy, key, bins)
panicOnError(err)
_ = err
if err == nil {
ch <- e
// fmt.Println(i)
w.Write([]byte(fmt.Sprintf("Vote")))
} else {
w.Write([]byte(fmt.Sprintf("Duplicate")))
}
}
示例5: statsBoss
func statsBoss() {
statsMap := map[string][]uint64{}
for {
select {
case s := <-stats:
if lst, exists := statsMap[s.ticker]; !exists {
statsMap[s.ticker] = []uint64{s.price}
} else {
statsMap[s.ticker] = append(lst, s.price)
}
case <-time.After(1 * time.Second):
for ticker, stats := range statsMap {
if len(stats) == 0 {
continue
}
sum := 0
for _, p := range stats {
sum += int(p)
}
key, _ := as.NewKey(NAMESPACE, STOCKS, ticker)
go db.Put(nil, key, as.BinMap{"price": sum / len(stats)})
}
// reset the stats
statsMap = map[string][]uint64{}
}
}
}
示例6: Get
// Get retrieves a value by key.
func (db DB) Get(key string) (interface{}, error) {
k, err := as.NewKey(db.namespace, db.set, key)
if err != nil {
return 0, err
}
return db.client.Get(db.p, k)
}
示例7: main
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
// defer client.Close()
client, err = as.NewClient("172.31.53.227", 3000)
fmt.Println(client)
panicOnError(err)
writePolicy = as.NewWritePolicy(0, 0)
ch = make(chan Event, 1)
key, err := as.NewKey("test", "totals", "test")
panicOnError(err)
// define some bins with data
bins := as.BinMap{
"value": 100,
}
err = client.Put(nil, key, bins)
panicOnError(err)
time.AfterFunc(1*time.Second, func() {
for i := 1; i < 24; i++ {
fmt.Println("starting worker %d", i)
go worker(ch)
}
})
http.HandleFunc("/vote", voteHandler)
http.HandleFunc("/loaderio-35df9c4fffde902e3b0e3e0115816d82.html", validationHandler)
http.ListenAndServe(":80", nil)
}
示例8: batchReads
/**
* Read records in one batch.
*/
func batchReads(
client *as.Client,
keyPrefix string,
binName string,
size int,
) {
// Batch gets into one call.
keys := make([]*as.Key, size)
for i := 0; i < size; i++ {
keys[i], _ = as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i+1))
}
records, err := client.BatchGet(nil, keys, binName)
shared.PanicOnError(err)
for i := 0; i < len(records); i++ {
key := keys[i]
record := records[i]
level := asl.ERR
var value interface{}
if record != nil {
level = asl.INFO
value = record.Bins[binName]
}
asl.Logger.LogAtLevel(level, "Record: ns=%s set=%s key=%s bin=%s value=%s",
key.Namespace(), key.SetName(), key.Value(), binName, value)
}
if len(records) != size {
log.Fatalf("Record size mismatch. Expected %d. Received %d.", size, len(records))
}
}
示例9: runExample
func runExample(client *as.Client) {
// Write initial record.
key, _ := as.NewKey(*shared.Namespace, *shared.Set, "opkey")
bin1 := as.NewBin("optintbin", 7)
bin2 := as.NewBin("optstringbin", "string value")
log.Printf("Put: namespace=%s set=%s key=%s bin1=%s value1=%s bin2=%s value2=%s",
key.Namespace(), key.SetName(), key.Value(), bin1.Name, bin1.Value, bin2.Name, bin2.Value)
client.PutBins(shared.WritePolicy, key, bin1, bin2)
// Add integer, write new string and read record.
bin3 := as.NewBin(bin1.Name, 4)
bin4 := as.NewBin(bin2.Name, "new string")
log.Println("Add: ", bin3.Value)
log.Println("Write: ", bin4.Value)
log.Println("Read:")
record, err := client.Operate(shared.WritePolicy, key, as.AddOp(bin3), as.PutOp(bin4), as.GetOp())
shared.PanicOnError(err)
if record == nil {
log.Fatalf(
"Failed to get: namespace=%s set=%s key=%s",
key.Namespace(), key.SetName(), key.Value())
}
binExpected := as.NewBin(bin3.Name, 11)
shared.ValidateBin(key, binExpected, record)
shared.ValidateBin(key, bin4, record)
}
示例10: runExample
func runExample(client *as.Client) {
// Set LuaPath
luaPath, _ := os.Getwd()
luaPath += "/udf/"
as.SetLuaPath(luaPath)
filename := "sum_single_bin"
regTask, err := client.RegisterUDFFromFile(nil, luaPath+filename+".lua", filename+".lua", as.LUA)
shared.PanicOnError(err)
// wait until UDF is created
shared.PanicOnError(<-regTask.OnComplete())
sum := 0
for i := 1; i <= keyCount; i++ {
sum += i
key, err := as.NewKey(*shared.Namespace, *shared.Set, i)
shared.PanicOnError(err)
bin1 := as.NewBin("bin1", i)
client.PutBins(nil, key, bin1)
}
t := time.Now()
stm := as.NewStatement(*shared.Namespace, *shared.Set)
res, err := client.QueryAggregate(nil, stm, filename, filename, "bin1")
shared.PanicOnError(err)
for rec := range res.Results() {
log.Printf("Result %f should equal %d\n", rec.Record.Bins["SUCCESS"], sum)
}
log.Println("Map/Reduce took", time.Now().Sub(t))
}
示例11: batchReadHeaders
/**
* Read record header data in one batch.
*/
func batchReadHeaders(
client *as.Client,
keyPrefix string,
size int,
) {
// Batch gets into one call.
keys := make([]*as.Key, size)
for i := 0; i < size; i++ {
keys[i], _ = as.NewKey(*shared.Namespace, *shared.Set, keyPrefix+strconv.Itoa(i+1))
}
records, err := client.BatchGetHeader(nil, keys)
shared.PanicOnError(err)
for i := 0; i < len(records); i++ {
key := keys[i]
record := records[i]
level := asl.ERR
generation := 0
expiration := 0
if record != nil && (record.Generation > 0 || record.Expiration > 0) {
level = asl.INFO
generation = record.Generation
expiration = record.Expiration
}
asl.Logger.LogAtLevel(level, "Record: ns=%s set=%s key=%s generation=%d expiration=%d",
key.Namespace(), key.SetName(), key.Value(), generation, expiration)
}
if len(records) != size {
log.Fatalf("Record size mismatch. Expected %d. Received %d.", size, len(records))
}
}
示例12: nextSeq
// Increment a bin, being used as a sequence generator.
func nextSeq(seq string) (int, error) {
keyId := fmt.Sprintf("%s:%s", SEQUENCES, seq)
key, err := as.NewKey(NAMESPACE, SEQUENCES, keyId)
if err != nil {
return 0, err
}
rec, err := db.Operate(
writePolicy,
key,
as.AddOp(as.NewBin("seq", 1)),
as.GetOpForBin("seq"),
)
if err != nil {
return 0, err
}
if seq, exists := rec.Bins["seq"]; !exists || int(seq.(int)) <= 0 {
return 0, fmt.Errorf("sequence not found: %s", seq)
}
return rec.Bins["seq"].(int), nil
}
示例13: AddBroker
// Add a new Broker
func (command *Command) AddBroker(r *http.Request, broker *m.Broker, done *bool) error {
*done = false
keyId := fmt.Sprintf("%s:%d", BROKERS, broker.Id)
key, _ := as.NewKey(NAMESPACE, BROKERS, keyId)
db.Delete(nil, key)
bins := as.BinMap{
"broker_id": broker.Id,
"broker_name": broker.Name,
"credit": broker.Credit,
}
policy := &as.WritePolicy{
BasePolicy: *as.NewPolicy(),
RecordExistsAction: as.CREATE_ONLY,
GenerationPolicy: as.NONE,
Generation: 0,
Expiration: 0,
SendKey: false,
}
if err := db.Put(policy, key, bins); err != nil {
return err
}
*done = true
return nil
}
示例14: Set
// Set stores a value by key.
// TODO(nslaughter): change name. Put is a better name because a Set is a thing.
func (db DB) Set(key string, value string) (interface{}, error) {
k, err := as.NewKey(db.namespace, db.set, key)
if err != nil {
return 0, err
}
bin := as.NewBin("", value)
db.client.PutBins(db.wp, k, bin)
return 1, nil
}
示例15: seed_db
func seed_db() {
println("Sedding db...")
var key *as.Key
println("Sedding stocks...")
// put stocks
key, _ = as.NewKey(NAMESPACE, STOCKS, "GOOG")
db.Put(nil, key, as.BinMap{
"ticker": "GOOG",
"quantity": int64(1e9),
"price": int(5200),
})
key, _ = as.NewKey(NAMESPACE, STOCKS, "APPL")
db.Put(nil, key, as.BinMap{
"ticker": "APPL",
"quantity": int64(1e9),
"price": 8200,
})
key, _ = as.NewKey(NAMESPACE, STOCKS, "FB")
db.Put(nil, key, as.BinMap{
"ticker": "FB",
"quantity": int64(1e9),
"price": 5200,
})
key, _ = as.NewKey(NAMESPACE, STOCKS, "MSFT")
db.Put(nil, key, as.BinMap{
"ticker": "MSFT",
"quantity": int64(1e9),
"price": 2100,
})
key, _ = as.NewKey(NAMESPACE, STOCKS, "GE")
db.Put(nil, key, as.BinMap{
"ticker": "GE",
"quantity": int64(1e9),
"price": 1100,
})
}