product_code.go
1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package redis
import (
"fmt"
"github.com/go-redis/redis"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-manufacture/pkg/constant"
"time"
)
func GenCode(ca CacheCode) (string, error) {
key := ca.CacheKey()
client := GetRedis()
result := client.Get(key)
index, err := result.Int()
if err == redis.Nil {
index = 1
err = nil
if ret := client.Set(key, index, ca.Expire()); ret.Err() != nil {
return "", ret.Err()
}
return ca.Format(index), nil
}
if err != nil {
return "", err
}
if ret := client.Incr(key); ret.Err() != nil {
return "", ret.Err()
} else {
index = int(ret.Val())
}
return ca.Format(index), nil
}
type CacheCode interface {
CacheKey() string
Expire() time.Duration
Format(index int) string
}
type ProductCodeCache struct {
CompanyId int
Time time.Time
}
func (ca ProductCodeCache) CacheKey() string {
str := fmt.Sprintf("%v:product-code:%v:%v", constant.CACHE_PREFIX, ca.CompanyId, ca.Time.Format("20060102"))
return str
}
func (ca ProductCodeCache) Format(index int) string {
if index <= 999 {
return fmt.Sprintf("CP%v%03d", ca.Time.Format("060102"), index)
}
return fmt.Sprintf("CP%v%d", ca.Time.Format("060102"), index)
}
func (ca ProductCodeCache) Expire() time.Duration {
return time.Hour * 24
}
func NewProductCodeCache(id int) ProductCodeCache {
return ProductCodeCache{
CompanyId: id,
Time: time.Now(),
}
}