Beispiel #1
0
func NewRedisClient(config *Config) (*RedisClient, error) {
	var client *redis.Client

	if config.RedisSentinel {
		client = redis.NewFailoverClient(&redis.FailoverOptions{
			MasterName:    config.RedisMasterName,
			SentinelAddrs: []string{config.RedisAddr},
			Password:      config.RedisPassword,
			DB:            config.RedisDB,
		})
	} else {
		client = redis.NewClient(&redis.Options{
			Addr:     config.RedisAddr,
			Password: config.RedisPassword,
			DB:       config.RedisDB,
		})
	}
	ps, err := client.Subscribe(channelName)

	if err != nil {
		return nil, err
	}

	rc := &RedisClient{
		client: client,
		pubsub: ps,
	}
	go rc.Receive()
	return rc, nil
}
func process(metric data.Metric, client *redis.Client) error {
	year, month, day := time.Now().UTC().Date()
	date := strconv.Itoa(year) + "-" + strconv.Itoa(int(month)) + "-" + strconv.Itoa(day)
	key := date + " " + metric.Metric
	err := client.Set(key, true, 0).Err()
	if err != nil {
		log.Fatalf("Failed to set metric connection. ERR: %+v", err)
	}
	log.Printf("Metric %+v", metric)
	return err
}
func acquireLock(client *redis.Client) bool {
	_, err := client.Watch(DIST_LOCK)
	if err != nil {
		log.Fatalf("Error watching distributed lock key. ERR: %+v", err)
		return false
	}
	value, err := client.Get(DIST_LOCK).Int64()
	if err != nil {
		log.Fatalf("Error getting distributed lock key. ERR: %+v", err)
		return false
	}
	if value == ACQUIRED {
		return false
	}
	multi := client.Multi()
	_, err = multi.Exec(func() error {
		err := multi.Set(DIST_LOCK, ACQUIRED, 0).Err()
		if err != nil {
			log.Fatalf("Error setting distributed lock key. ERR: %+v", err)
			return err
		}
		return nil
	})
	if err != nil {
		log.Fatalf("Error executing the set distributed lock key. ERR: %+v", err)
		return false
	}
	return true
}
func aggregate(client *redis.Client, year int, month int) error {
	log.Println("Curating logs...")
	yearMonth := strconv.Itoa(year) + "-" + strconv.Itoa(month)
	key := yearMonth + "-*"
	keys, err := client.Keys(key).Result()
	if err != nil {
		log.Printf("Failed to set metric connection. ERR: %+v", err)
		return err
	}

	if len(keys) == 0 {
		return nil
	}

	events := getEvents(keys)
	monthlyEvent := struct {
		Events []string
	}{
		events,
	}

	byteContent, err := json.Marshal(monthlyEvent)
	if err != nil {
		log.Println("Failed to set all event under single key. ERR: %+v", err)
		return err
	}

	err = client.Set(yearMonth, byteContent, 0).Err()
	if err != nil {
		log.Println("Failed to set all event under single key. ERR: %+v", err)
		return err
	}

	err = client.Del(keys...).Err()
	if err != nil {
		log.Println("Failed to delete all event in the past month. ERR: %+v", err)
		return err
	}
	return err
}
func releaseLock(client *redis.Client) {
	err := client.Set(DIST_LOCK, 0, 0).Err()
	if err != nil {
		log.Fatalf("Error in releasing the lock. ERR: %+v", err)
	}
}