Fix Redis stats storage concurrency issues (#478)

This commit is contained in:
Yaroslav "Zorg" Zborovsky 2020-02-29 11:14:44 +02:00 committed by GitHub
parent cbab088ed4
commit b58386704c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 15 deletions

View File

@ -46,47 +46,44 @@ func (s *Storage) Init() error {
return err
}
// Set initial values
s.Reset()
return nil
}
// Reset Client storage.
func (s *Storage) Reset() {
redisClient.Set(storage.TotalCountKey, strconv.Itoa(0), 0)
redisClient.Set(storage.IosSuccessKey, strconv.Itoa(0), 0)
redisClient.Set(storage.IosErrorKey, strconv.Itoa(0), 0)
redisClient.Set(storage.AndroidSuccessKey, strconv.Itoa(0), 0)
redisClient.Set(storage.AndroidErrorKey, strconv.Itoa(0), 0)
redisClient.Set(storage.TotalCountKey, int64(0), 0)
redisClient.Set(storage.IosSuccessKey, int64(0), 0)
redisClient.Set(storage.IosErrorKey, int64(0), 0)
redisClient.Set(storage.AndroidSuccessKey, int64(0), 0)
redisClient.Set(storage.AndroidErrorKey, int64(0), 0)
}
// AddTotalCount record push notification count.
func (s *Storage) AddTotalCount(count int64) {
total := s.GetTotalCount() + count
redisClient.Set(storage.TotalCountKey, strconv.Itoa(int(total)), 0)
redisClient.IncrBy(storage.TotalCountKey, count)
}
// AddIosSuccess record counts of success iOS push notification.
func (s *Storage) AddIosSuccess(count int64) {
total := s.GetIosSuccess() + count
redisClient.Set(storage.IosSuccessKey, strconv.Itoa(int(total)), 0)
redisClient.IncrBy(storage.IosSuccessKey, count)
}
// AddIosError record counts of error iOS push notification.
func (s *Storage) AddIosError(count int64) {
total := s.GetIosError() + count
redisClient.Set(storage.IosErrorKey, strconv.Itoa(int(total)), 0)
redisClient.IncrBy(storage.IosErrorKey, count)
}
// AddAndroidSuccess record counts of success Android push notification.
func (s *Storage) AddAndroidSuccess(count int64) {
total := s.GetAndroidSuccess() + count
redisClient.Set(storage.AndroidSuccessKey, strconv.Itoa(int(total)), 0)
redisClient.IncrBy(storage.AndroidSuccessKey, count)
}
// AddAndroidError record counts of error Android push notification.
func (s *Storage) AddAndroidError(count int64) {
total := s.GetAndroidError() + count
redisClient.Set(storage.AndroidErrorKey, strconv.Itoa(int(total)), 0)
redisClient.IncrBy(storage.AndroidErrorKey, count)
}
// GetTotalCount show counts of all notification.

View File

@ -1,6 +1,7 @@
package redis
import (
"sync"
"testing"
c "github.com/appleboy/gorush/config"
@ -55,4 +56,17 @@ func TestRedisEngine(t *testing.T) {
redis.Reset()
val = redis.GetAndroidError()
assert.Equal(t, int64(0), val)
// test concurrency issues
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
redis.AddTotalCount(1)
wg.Done()
}()
}
wg.Wait()
val = redis.GetTotalCount()
assert.Equal(t, int64(10), val)
}