github.com/mad-app/mattermost-server@v5.11.1+incompatible/store/redis_supplier.go (about)

     1  // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
     2  // See License.txt for license information.
     3  
     4  package store
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/gob"
     9  
    10  	"time"
    11  
    12  	"github.com/go-redis/redis"
    13  	"github.com/mattermost/mattermost-server/mlog"
    14  )
    15  
    16  const REDIS_EXPIRY_TIME = 30 * time.Minute
    17  
    18  type RedisSupplier struct {
    19  	next   LayeredStoreSupplier
    20  	client *redis.Client
    21  }
    22  
    23  func GetBytes(key interface{}) ([]byte, error) {
    24  	var buf bytes.Buffer
    25  	enc := gob.NewEncoder(&buf)
    26  	err := enc.Encode(key)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  	return buf.Bytes(), nil
    31  }
    32  
    33  func DecodeBytes(input []byte, thing interface{}) error {
    34  	dec := gob.NewDecoder(bytes.NewReader(input))
    35  	return dec.Decode(thing)
    36  }
    37  
    38  func NewRedisSupplier() *RedisSupplier {
    39  	supplier := &RedisSupplier{}
    40  
    41  	supplier.client = redis.NewClient(&redis.Options{
    42  		Addr:     "localhost:6379",
    43  		Password: "",
    44  		DB:       0,
    45  	})
    46  
    47  	if _, err := supplier.client.Ping().Result(); err != nil {
    48  		mlog.Error("Unable to ping redis server: " + err.Error())
    49  		return nil
    50  	}
    51  
    52  	return supplier
    53  }
    54  
    55  func (s *RedisSupplier) save(key string, value interface{}, expiry time.Duration) error {
    56  	if bytes, err := GetBytes(value); err != nil {
    57  		return err
    58  	} else {
    59  		if err := s.client.Set(key, bytes, expiry).Err(); err != nil {
    60  			return err
    61  		}
    62  	}
    63  	return nil
    64  }
    65  
    66  func (s *RedisSupplier) load(key string, writeTo interface{}) (bool, error) {
    67  	if data, err := s.client.Get(key).Bytes(); err != nil {
    68  		if err == redis.Nil {
    69  			return false, nil
    70  		} else {
    71  			return false, err
    72  		}
    73  	} else {
    74  		if err := DecodeBytes(data, writeTo); err != nil {
    75  			return false, err
    76  		}
    77  	}
    78  	return true, nil
    79  }
    80  
    81  func (s *RedisSupplier) SetChainNext(next LayeredStoreSupplier) {
    82  	s.next = next
    83  }
    84  
    85  func (s *RedisSupplier) Next() LayeredStoreSupplier {
    86  	return s.next
    87  }