src: Add DMA localagent
[barometer.git] / src / dma / pkg / common / redispool.go
1 /*
2  * Copyright 2018 NEC Corporation
3  *
4  *   Licensed under the Apache License, Version 2.0 (the "License");
5  *   you may not use this file except in compliance with the License.
6  *   You may obtain a copy of the License at
7  *
8  *       http://www.apache.org/licenses/LICENSE-2.0
9  *
10  *   Unless required by applicable law or agreed to in writing, software
11  *   distributed under the License is distributed on an "AS IS" BASIS,
12  *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  *   See the License for the specific language governing permissions and
14  *   limitations under the License.
15  */
16
17 package common
18
19 import (
20         "github.com/go-redis/redis"
21         "log"
22 )
23
24 // RedisPool is an implementation of Pool by redis.
25 type RedisPool struct {
26         Client *redis.Client
27 }
28
29 // Set is to set data in redis.
30 func (thisPool RedisPool) Set(key string, data string) error {
31         key = redisLabel + "/" + key
32         err := thisPool.Client.Set(key, data, 0).Err()
33         if err != nil {
34                 log.Printf("redis Set error: %s", err)
35         }
36         return err
37 }
38
39 // Get is to get data in redis.
40 func (thisPool RedisPool) Get(key string) (string, error) {
41         key = redisLabel + "/" + key
42         value, err := thisPool.Client.Get(key).Result()
43         if err != nil {
44                 log.Printf("redis Get error: %s", err)
45         }
46         return value, err
47 }
48
49 // Del is to delete data in redis.
50 func (thisPool RedisPool) Del(key string) error {
51         key = redisLabel + "/" + key
52         err := thisPool.Client.Del(key).Err()
53         if err != nil {
54                 log.Printf("redis Del error: %s", err)
55         }
56         return err
57 }
58
59 // DelAll is to delete all data, begins with <redisLabel>, in redis.
60 func (thisPool RedisPool) DelAll() error {
61         pattern := redisLabel + "/*"
62
63         keys, err := thisPool.Client.Keys(pattern).Result()
64         if err != nil {
65                 log.Printf("redis Keys error :%s", err)
66         }
67
68         for _, v := range keys {
69                 thisPool.Client.Del(v)
70         }
71         return err
72 }