예제 #1
0
파일: ciao.go 프로젝트: chronicaww/Go-Redis
func main() {

	// create the client.  Here we are using a synchronous client.
	// Using the default ConnectionSpec, we are specifying the client to connect
	// to db 13 (e.g. SELECT 13), and a password of go-redis (e.g. AUTH go-redis)

	spec := redis.DefaultSpec().Db(13).Password("go-redis")
	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		log.Println("failed to create the client", e)
		return
	}

	key := "examples/hello/user.name"
	value, e := client.Get(key)
	if e != nil {
		log.Println("error on Get", e)
		return
	}

	if value == nil {
		fmt.Printf("\nHello, don't believe we've met before!\nYour name? ")
		reader := bufio.NewReader(os.Stdin)
		user, _ := reader.ReadString(byte('\n'))
		if len(user) > 1 {
			user = user[0 : len(user)-1]
			value = []byte(user)
			client.Set(key, value)
		} else {
			fmt.Printf("vafanculo!\n")
			return
		}
	}
	fmt.Printf("Hey, ciao %s!\n", fmt.Sprintf("%s", value))
}
예제 #2
0
func RedisPush(rawtokenstring string) int {
	spec := redis.DefaultSpec().Password("go-redis")
	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		fmt.Println("error creating client for: ", e)
	}
	defer client.Quit()
	//pidString := strconv.Itoa(cmdI.Process.Pid)
	decryptedToken, err := jwt.Parse(rawtokenstring, func(token *jwt.Token) (interface{}, error) {
		return []byte(secretKey), nil
	})
	//fmt.Printf("token strings\nRaw: [%s]\nHeader: [%s]\nSignature: [%s]\n", decryptedToken.Raw, decryptedToken.Header, decryptedToken.Signature)

	//check if no error and valid token
	if err == nil && decryptedToken.Valid {
		fmt.Println("token is valid and not expired")

	} else {
		fmt.Println("Not valid: ", err)
		return 0
	}

	userID := decryptedToken.Claims["id"].(string)
	//fmt.Println("redis func userid: " + userID + "\n redis func raw: " + decryptedToken.Raw)
	var buf bytes.Buffer
	buf.Write([]byte(decryptedToken.Raw))
	e = client.Hset("clients/token", userID, buf.Bytes())
	//to retrieve token in redis-cli, do hget clients/tokens legacy
	if e != nil {
		fmt.Println("error writing to list")
		return 0
	}
	return 1
}
예제 #3
0
// Use a single redis.AsyncClient with specified number
// of workers to bench concurrent load on the async client
func benchTask(taskspec taskSpec, iterations int, workers int, printReport bool) (delta int64, err os.Error) {
	signal := make(chan int, workers) // Buffering optional but sensible.
	spec := redis.DefaultSpec().Db(13).Password("go-redis")
	client, e := redis.NewAsynchClientWithSpec(spec)
	if e != nil {
		log.Println("Error creating client for worker: ", e)
		return -1, e
	}
	//    defer client.Quit()        // will be deprecated soon
	defer client.RedisClient().Quit()

	t0 := time.Nanoseconds()
	for i := 0; i < workers; i++ {
		id := fmt.Sprintf("%d", i)
		go taskspec.task(id, signal, client, iterations)
	}
	for i := 0; i < workers; i++ {
		<-signal
	}
	delta = time.Nanoseconds() - t0
	//	for i := 0; i < workers; i++ {
	//		clients[i].Quit()
	//	}
	//
	if printReport {
		report("concurrent "+taskspec.name, delta, iterations*workers)
	}

	return
}
예제 #4
0
// Reflect over the methods defined in redis.Client
// and send back as []string (tolowercase)
// TOOD get rid of redundant code in switch
// (REVU: needs minor update to core code)
func getDefinedMethods(ctype clientType) (map[string]string, *error_) {

	var mmap = map[string]string{}

	spec := redis.DefaultSpec().Db(13).Password("go-redis")

	var e redis.Error
	var client interface{}

	switch ctype {
	case sync:
		client, e = redis.NewSynchClientWithSpec(spec)
	case async:
		client, e = redis.NewAsynchClientWithSpec(spec)
	}
	if e != nil {
		log.Println("ignoring - ", e)
	}
	if client == nil {
		return mmap, &error_{"client is nil", nil}
	} else {
		defer client.(redis.RedisClient).Quit()
	}

	tc := reflect.TypeOf(client)
	nm := tc.NumMethod()

	for i := 0; i < nm; i++ {
		m := tc.Method(i)
		mname := strings.ToLower(m.Name)
		mmap[mname] = mname
	}
	return mmap, nil
}
예제 #5
0
func spamChat1(chanKey string) {
	fmt.Println("spamchat being called")
	spec := redis.DefaultSpec().Password("go-redis")
	client, e := redis.NewAsynchClientWithSpec(spec)
	if e != nil {
		fmt.Print("Error creating spam client for: ", e)
	}
	defer client.Quit()

	for i := 0; i < 1000000; i++ {
		var fr redis.FutureInt64
		//var fr2 redis.FutureBool
		var buf bytes.Buffer
		buf.Write([]byte("hello" + string(i)))
		bt := buf.Bytes()
		fr, e = client.Publish("chat", bt)
		//fmt.Println("we got past 2 publishes")
		if e != nil {
			fmt.Println("error in publishing: ", e)
		}
		_, e = client.Rpush("chatlog", bt)
		if e != nil {
			fmt.Println("error in storing list: ", e)
		}

		numRecieved, _ := fr.Get()
		//fmt.Println(numRecieved)
		//fr2.Get()
	}
}
예제 #6
0
func NewRedisAsyncClient() redis.AsyncClient {
	spec := redis.DefaultSpec().Db(0).Host("10.174.178.235")
	client, err := redis.NewAsynchClientWithSpec(spec)
	if err != nil {
		panic(err)
	}
	return client
}
예제 #7
0
파일: database.go 프로젝트: c00w/Calendar
func getclient() redis.Client {
	spec := redis.DefaultSpec().Db(1)
	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		log.Fatal(e)
	}
	return client
}
예제 #8
0
func Do(w http.ResponseWriter, req *http.Request) {
	taskid := req.URL.Query().Get("taskid") // 通知主删除这个任务
	var spec *redis.ConnectionSpec = redis.DefaultSpec()
	ackip := utils.Cfg.GetString("redisIpACK")
	ackport := utils.Cfg.GetInt("redisIpACK")
	spec.Host(ackip)
	spec.Port(ackport)
	redis1.SyncPublish(spec, "ACK", taskid)
}
예제 #9
0
/// 创建新的日志记录器.
///
/// @param servAddr redis服务器地址
/// @param servPort redis服务器端口
/// @param logLev 限制日志输出级别
/// @return 成功则返回日志记录器,同时error为nil.
func NewLogger(servAddr string, servPort int, logLev uint8) (*Logger, error) {
	spec := redis.DefaultSpec().Host(servAddr).Port(servPort)
	cli, err := redis.NewSynchClientWithSpec(spec)

	if nil != err {
		return nil, err
	}

	return &Logger{logLev, servAddr, servPort, cli, new(defaultFormatter)}, nil
}
예제 #10
0
// connection spec used in tests, using db 13 and password 'go-redis'.
// db 13 will be repeatedly flushed, as noted elsewhere.
func _test_getDefConnSpec() *redis.ConnectionSpec {

	host := "localhost"
	port := 6379
	db := 13
	password := "******"

	connspec := redis.DefaultSpec().Host(host).Port(port).Db(db).Password(password)
	return connspec
}
예제 #11
0
func NewReportInfo(mid string, mt string, intv int16, reportAddr string, reportPort int) (*ReportInfo, error) {

	spec := redis.DefaultSpec().Host(reportAddr).Port(reportPort)
	cli, err := redis.NewSynchClientWithSpec(spec)

	if err != nil {
		return nil, err
	}

	return &ReportInfo{mid, mt, intv, cli}, nil
}
예제 #12
0
func makeConcurrentClients(workers int) (clients []redis.Client, err error) {
	clients = make([]redis.Client, workers)
	for i := 0; i < workers; i++ {
		spec := redis.DefaultSpec().Db(13).Password("go-redis")
		client, e := redis.NewSynchClientWithSpec(spec)
		if e != nil {
			log.Println("Error creating client for worker: ", e)
			return nil, e
		}
		clients[i] = client
	}
	return
}
예제 #13
0
func makeConcurrentClients(workers int) (clients []redis.Client, err os.Error) {
    clients = make([]redis.Client, workers);
    for i := 0; i < workers; i++ {
		spec := redis.DefaultSpec().Db(13);
		client, e := redis.NewSynchClientWithSpec (spec);
		if e != nil {
			log.Stderr ("Error creating client for worker: ", e);
			return nil, e;
		}
		clients[i] = client;
    }
    return;
}
예제 #14
0
func doOne(cnt int) error {

	var delta time.Duration
	spec := redis.DefaultSpec().Db(13).Password("go-redis")

	fmt.Printf("\n\n=== Bench synchclient ================ 1 Client -- %d opts --- \n", cnt)
	fmt.Println()

	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		return onError("on NewSynchClient call: ", e)
	}
	if client == nil {
		return failedTest("NewSynchClient returned nil!")
	}
	//	defer client.Quit()   // will be deprecated soon
	defer client.RedisClient().Quit()

	client.Flushdb()

	delta = doPing(client, cnt)
	report("PING", delta, cnt)

	delta = doIncr(client, cnt)
	report("INCR", delta, cnt)

	delta = doSet(client, cnt)
	report("SET", delta, cnt)

	delta = doGet(client, cnt)
	report("GET", delta, cnt)

	delta = doSadd(client, cnt)
	report("SADD", delta, cnt)

	delta = doLpush(client, cnt)
	report("LPUSH", delta, cnt)

	delta = doRpush(client, cnt)
	report("RPUSH", delta, cnt)

	delta = doLpop(client, cnt)
	report("LPOP", delta, cnt)

	delta = doRpop(client, cnt)
	report("RPOP", delta, cnt)

	return nil
}
예제 #15
0
파일: universe.go 프로젝트: onewland/gomud
func NewUniverse(dbNo int) *Universe {
	u := new(Universe)
	u.Players = make(map[int]*Player)
	u.Rooms = make(map[int]*Room)
	u.children = NewFlexContainer("Persistents", "TimeListeners")
	spec := redis.DefaultSpec().Db(dbNo)
	client, err := redis.NewSynchClientWithSpec(spec)
	if err != nil {
		panic(err)
	} else {
		u.dbConn = client
		u.Store = NewTinyDB(client)
	}
	return u
}
예제 #16
0
func doOne(cnt int) os.Error {

	var delta int64
	spec := redis.DefaultSpec().Db(13)

	fmt.Printf("\n\n=== Bench synchclient ================ 1 Client -- %d opts --- \n", cnt)
	fmt.Println()

	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		return onError("on NewSynchClient call: ", e)
	}
	if client == nil {
		return failedTest("NewSynchClient returned nil!")
	}

	client.Flushdb()

	delta = doPing(client, cnt)
	report("PING", delta, cnt)

	delta = doIncr(client, cnt)
	report("INCR", delta, cnt)

	delta = doSet(client, cnt)
	report("SET", delta, cnt)

	delta = doGet(client, cnt)
	report("GET", delta, cnt)

	delta = doSadd(client, cnt)
	report("SADD", delta, cnt)

	delta = doLpush(client, cnt)
	report("LPUSH", delta, cnt)

	delta = doRpush(client, cnt)
	report("RPUSH", delta, cnt)

	delta = doLpop(client, cnt)
	report("LPOP", delta, cnt)

	delta = doRpop(client, cnt)
	report("RPOP", delta, cnt)

	client.Quit()
	return nil
}
예제 #17
0
파일: app.go 프로젝트: rmoorman/web-bench
func main() {
	runtime.GOMAXPROCS(16)
	key = "user_data_2"
	spec := redis.DefaultSpec().Db(0).Host("10.174.178.235")
	client, err := redis.NewAsynchClientWithSpec(spec)
	if err != nil {
		panic(err)
	}
	primeKey(key, client)
	defer client.Quit()
	handler := func(w http.ResponseWriter, r *http.Request) {
		responseHandler(w, r, client)
	}
	http.HandleFunc("/", handler)
	http.ListenAndServe(":80", nil)
}
예제 #18
0
func InitRedis() {
	redisnum := utils.Cfg.GetInt("redisNum")
	for i := 0; i < redisnum; i++ {
		ip := utils.Cfg.GetString("redisIp" + strconv.Itoa(i))
		port := utils.Cfg.GetInt("redisPort" + strconv.Itoa(i))
		spec[i] = redis.DefaultSpec()
		spec[i].Host(ip)
		spec[i].Port(port)
		sub[i], errtopic = redis.NewPubSubClientWithSpec(spec[i])
		if errtopic != nil {
			//			log.Println("failed to create the sync client", e)
			fmt.Printf("Error ", errtopic)
		}
		sub[i].Subscribe(utils.Cfg.GetString("slavename")) //队列名为从的名字
		go getmessage(i)
	}
}
예제 #19
0
func main() {
	runtime.GOMAXPROCS(16)
	key = "user_data_2"
	spec := redis.DefaultSpec().Db(0).Host("10.174.178.235")
	primeClient, err := redis.NewAsynchClientWithSpec(spec)
	if err != nil {
		panic(err)
	}
	primeKey(key, primeClient)
	log.Println("Key primed and ready")
	defer primeClient.Quit()
	pool = NewClientPool(100)
	handler := func(w http.ResponseWriter, r *http.Request) {
		responseHandler(w, r)
	}
	http.HandleFunc("/", handler)
	http.ListenAndServe(":80", nil)
}
예제 #20
0
func main() {

	// Parse command-line flags; needed to let flags used by Go-Redis be parsed.
	flag.Parse()

	// create the client.  Here we are using a synchronous client.
	// Using the default ConnectionSpec, we are specifying the client to connect
	// to db 13 (e.g. SELECT 13), and a password of go-redis (e.g. AUTH go-redis)

	spec := redis.DefaultSpec().Password("go-redis")
	channel := "example/pubsub/channel"

	// publish using sync client
	syncPublish(spec, channel)

	// publish using async client
	asyncPublish(spec, channel)

}
예제 #21
0
func connectClient(chanKey string) redis.PubSubChannel {

	spec := redis.DefaultSpec().Password("go-redis")
	client, e := redis.NewPubSubClientWithSpec(spec)
	if e != nil {
		fmt.Print("Error creating client for: ", e)
	}
	defer client.Quit()
	fmt.Println("before subbing")
	client.Subscribe("chat")
	fmt.Println("after subbing")
	return client.Messages("chat")
	//fmt.Println(string(<-client.Messages("chat")))
	//fmt.Println(string(<-client.Messages("chat")))
	//for {
	//	chatbuf := bytes.NewBuffer(<-client.Messages("chat"))
	//	chatbuf.WriteTo(os.Stdout)
	//	}
}
예제 #22
0
파일: model.go 프로젝트: nono/Goldorak.Go
func Connect() *Connection {
	fullname := GetConfig("appname")
	database := GetConfig("database")
	db, err := strconv.Atoi(database)
	if err != nil {
		log.Stderrf("Can't read the database", err)
		return nil
	}
	spec := redis.DefaultSpec().Db(db)
	cli, err := redis.NewSynchClientWithSpec(spec)
	if err != nil {
		log.Stderrf("Can't connect to the database", err)
		return nil
	}
	err = cli.Ping()
	if err != nil {
		log.Stderrf("Can't ping the database", err)
		return nil
	}
	return &Connection{fullname, db, cli}
}
예제 #23
0
func NewClient(cspec *ClientSpec) Client {
	if cspec == nil {
		cspec = DefaultSpec()
	}

	cspec.Queue = fmt.Sprintf("resque:queue:%s", cspec.Queue)

	spec := redis.DefaultSpec()
	spec.Host(strings.Split(cspec.RedisLocation, ":")[0])
	i, err := strconv.Atoi(strings.Split(cspec.RedisLocation, ":")[1])
	if err != nil {
		log.Panicln("Invalid port", cspec.RedisLocation, err)
	}
	spec.Port(i)
	client, e := redis.NewSynchClientWithSpec(spec)
	if e != nil {
		log.Panicln("failed to create the client", e)
	}
	return Client{
		cspec,
		client,
	}
}
예제 #24
0
// Use a single redis.AsyncClient with specified number
// of workers to bench concurrent load on the async client
func benchTask(taskspec taskSpec, iterations int, workers int, printReport bool) (delta time.Duration, err error) {
	// channel to signal completion
	signal := make(chan int, workers)

	// spec and initialize an AsyncClient
	// will flush your db13 as noted in README ..
	spec := redis.DefaultSpec().Db(13).Password("go-redis")
	client, e := redis.NewAsynchClientWithSpec(spec)
	if e != nil {
		log.Println("Error creating client for worker: ", e)
		return -1, e
	}

	defer client.Quit()

	// panics
	setup(client)

	t0 := time.Now()
	for i := 0; i < workers; i++ {
		id := fmt.Sprintf("%d", i)
		go taskspec.task(id, signal, client, iterations)
	}

	// wait for completion
	for i := 0; i < workers; i++ {
		<-signal
	}
	delta = time.Now().Sub(t0)

	if printReport {
		report(taskspec.name, workers, delta, iterations*workers)
	}

	return
}
예제 #25
0
파일: main.go 프로젝트: vassilux/vorimport
func importJob() {
	//
	db := mysql.New("tcp", "", config.DbMySqlHost, config.DbMySqlUser, config.DbMySqlPassword, config.DbMySqlName)
	log.Debugf("Connecting to the database %s %s %s %s.", config.DbMySqlHost, config.DbMySqlUser, config.DbMySqlPassword, config.DbMySqlName)
	//
	err := db.Connect()
	if err != nil {
		sendMySqlEventNotification(MYSQKO)
		log.Criticalf("Can't connect to the mysql database error : %s.", err)
		return
	}
	sendMySqlEventNotification(MYSQOK)
	log.Debug("Connected to the mysql database with success.")
	//
	session, err := mgo.Dial(config.MongoHost)
	if err != nil {
		log.Debugf("Can't connect to the mongo database error : %s.", err)
		sendMongoEventNotification(MONGKO)
		return
	}
	session.SetMode(mgo.Monotonic, true)
	defer session.Close()
	sendMongoEventNotification(MONGOK)
	log.Debug("Connected to the mongo database with success.")
	//
	err = executeCustomRequests(db)
	if err != nil {
		log.Errorf("Error to execute customise request : %s", err)
		log.Flush()
		os.Exit(1)
	}
	//
	cdrs, err := getMysqlCdr(db)
	//
	if err != nil {
		log.Criticalf("Can not get records from mysql cause error [%s].", err)
		log.Flush()
		os.Exit(1)
	}
	log.Tracef("Start records parcing.")
	//
	var incommingCount = 0
	var outgoingCount = 0

	for _, cdr := range cdrs {
		cdr.AsteriskId = config.AsteriskID
		var datetime = cdr.Calldate.Format(time.RFC3339)
		log.Tracef("Get raw cdr for the date [%s], the clid [%s] and the context [%s] from asterisk [%s]", datetime, cdr.ClidNumber, cdr.Dcontext, cdr.AsteriskId)
		//var cel Cel
		//cel, err = getMySqlCel(db, cdr.Uniqueid)
		var inoutstatus, err = getInOutStatus(cdr)
		if err != nil {
			log.Criticalf("Get error[%s]. Please check your configuration file.", err)
			log.Flush()
			os.Exit(1)
		}
		if inoutstatus == 1 {
			outgoingCount++
		} else if inoutstatus == 2 {
			incommingCount++
		}
		cdr.InoutStatus = inoutstatus
		var dispostionCode = DIC_DISPOSITION[cdr.DispositionStr]

		if dispostionCode > 0 {
			cdr.Disposition = DISPOSITION_TRANSLATION[dispostionCode]
		} else {
			cdr.Disposition = 0
		}

		//if cel.EventTime > 0 {
		//	//extract the timezone offset
		//	cdr.AnswerWaitTime = int(cel.EventTime - cdr.Calldate.Unix() - timeZoneOffset)
		//}
		//
		callDetails, err := getMySqlCallDetails(db, cdr.Uniqueid)
		if err != nil {
			log.Criticalf("Try to get the call details but get the error[%s].", err)
			log.Flush()
			os.Exit(1)
		}
		//
		log.Tracef("Get [%d] details records for the call with uniqueid [%s].", len(callDetails), cdr.Uniqueid)
		if callDetails != nil {
			cdr.CallDetails = callDetails
		}
		//

		if cdr.InoutStatus == DIRECTION_CALL_IN {
			var did = ""
			var peer = ""
			var exten = ""

			if len(cdr.CallDetails) == 0 && cdr.Dnid != "" {
				//a workaround if I can get cel records
				did = cdr.Dnid
				log.Tracef("Force did from cdr dnid [%s].", did)
			}

			for i := range cdr.CallDetails {
				var callDetail = cdr.CallDetails[i]
				if i == 0 && callDetail.EventType == "CHAN_START" {
					exten = callDetail.Exten
					did = callDetail.Exten
				}

				if callDetail.EventType == "ANSWER" && exten == callDetail.CidDnid && did == "" {
					//try to find did
					did = callDetail.CidDnid

				} else if callDetail.EventType == "BRIDGE_START" {
					//bridge start gives the time before answer
					cdr.AnswerWaitTime = int(callDetail.EventTime.Unix() - cdr.Calldate.Unix())
					peer = getPeerFromChannel(callDetail.Peer)

				} else if callDetail.EventType == "BRIDGE_END" && peer == "" {
					//idea to find the last BRIDGE_END event and get the extention from it
					peer = getPeerFromChannel(callDetail.Peer)
					break
				}
			}

			if peer == "" {
				peer = getPeerFromChannel(cdr.Dstchannel)
			}

			if peer == "" {
				//can be case that the call is not answered
				peer = cdr.Dst
			}

			cdr.Peer = peer

			//there is a possibility to have for incomming call a peer for the did number
			//this is dependes of the customer configuration
			//try to find a did value from database defined by the customer
			err := isDid(session, did)

			if err == nil {
				cdr.Did = did
			} else {
				cdr.Did = ""
			}

			log.Tracef("Did [%s] and peer [%s] for the call with uniqueid [%s].\n", did, peer, cdr.Uniqueid)

			if cdr.Dst == "s" && peer != "" {
				//
				cdr.Dst = cdr.Peer
			}

		} //end of the incomming call process
		//
		//
		err = importCdrToMongo(session, cdr)
		var importedStatus = 1
		if err != nil {
			log.Errorf("Can't import cdr to mongo [%v].", err)
			log.Flush()
			os.Exit(1)
		}
		//
		log.Debugf("Import executed for unique id [%s] with code : [%d], try process the mysql updating.\n",
			cdr.Uniqueid, importedStatus)

		err = udpateMySqlCdrImportStatus(db, cdr.Uniqueid, 1)

		if err != nil {
			log.Errorf("Can't update the import status for the call with unique id [%s].", cdr.Uniqueid)
			log.Flush()
			os.Exit(1)
		}

		err = deleteMySqlCelRecord(db, cdr.Uniqueid)
		if err != nil {
			log.Errorf("Can't delete cel records for uniqueid[%s].", cdr.Uniqueid)
		}

	}
	//
	log.Trace("End of cdr parsing.\n")
	//
	spec := redis.DefaultSpec()
	channel := "channel_cdr"
	//
	if incommingCount > 0 {
		syncPublish(spec, channel, "cdrincomming")
	}

	if outgoingCount > 0 {
		syncPublish(spec, channel, "cdroutgoing")
	}
	//
}
예제 #26
0
// Test ConnectionSpec uses redis db 13 and assumes AUTH password go-redis
func getTestConnSpec() *redis.ConnectionSpec {
	spec := redis.DefaultSpec()
	spec.Password("go-redis").Db(13)
	return spec
}