8000 Use cache · invisiblecoder99/livego@d875076 · GitHub
[go: up one dir, main page]

Skip to content

Commit d875076

Browse files
committed
Use cache
1 parent 1b3a45d commit d875076

File tree

8 files changed

+64
-125
lines changed

8 files changed

+64
-125
lines changed

.gitignore

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# Created by .ignore support plugin (hsz.mobi)
22
.idea
33
dist
4-
room_keys.json
54
.vscode
65
.tmp
7-
vendor
6+
vendor

Dockerfile

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ COPY . .
66
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o livego .
77

88
FROM alpine:latest
9-
LABEL maintainer="Ruben Cid Lara <rubencidlara@gmail.com>"
109
RUN mkdir -p /app/config
1110
WORKDIR /app
1211
ENV RTMP_PORT 1935

configure/channel.go

Lines changed: 39 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,112 +1,62 @@
11
package configure
22

33
import (
4-
"encoding/json"
54
"fmt"
6-
"io/ioutil"
75
"log"
86
"math/rand"
9-
"sync"
10-
"time"
117

128
"github.com/go-redis/redis/v7"
9+
"github.com/patrickmn/go-cache"
1310
)
1411

15-
var RoomKeys = LoadRoomKey(*GetKeyFile())
12+
var RoomKeys *RoomKeysType
1613

1714
var roomUpdated = false
1815

19-
var saveInFile = true
20-
var redisCli *redis.Client
16+
var saveInLocal = true
17+
18+
type RoomKeysType struct {
19+
redisCli *redis.Client
20+
localCache *cache.Cache
21+
}
2122

2223
func Init() {
23-
saveInFile = GetRedisAddr() == nil
24-
25-
rand.Seed(time.Now().UnixNano())
26-
if saveInFile {
27-
go func() {
28-
for {
29-
time.Sleep(15 * time.Second)
30-
if roomUpdated {
31-
RoomKeys.Save(*roomKeySaveFile)
32-
roomUpdated = false
33-
}
34-
}
35-
}()
24+
saveInLocal = GetRedisAddr() == nil
25+
26+
RoomKeys = &RoomKeysType{
27+
localCache: cache.New(cache.NoExpiration, 0),
28+
}
3629

30+
if saveInLocal {
3731
return
3832
}
3933

40-
redisCli = redis.NewClient(&redis.Options{
34+
RoomKeys.redisCli = redis.NewClient(&redis.Options{
4135
Addr: *GetRedisAddr(),
4236
Password: *GetRedisPwd(),
4337
DB: 0,
4438
})
4539

46-
_, err := redisCli.Ping().Result()
40+
_, err := RoomKeys.redisCli.Ping().Result()
4741
if err != nil {
4842
panic(err)
4943
}
5044

5145
log.Printf("Redis connected")
5246
}
5347

54-
type RoomKeysType struct {
55-
mapChanKey sync.Map
56-
mapKeyChan sync.Map
57-
}
58-
59-
func LoadRoomKey(f string) *RoomKeysType {
60-
result := &RoomKeysType{
61-
mapChanKey: sync.Map{},
62-
mapKeyChan: sync.Map{},
63-
}
64-
raw := map[string]string{}
65-
content, err := ioutil.ReadFile(f)
66-
if err != nil {
67-
log.Printf("Failed to read file %s for room keys", f)
68-
return result
69-
}
70-
if json.Unmarshal(content, &raw) != nil {
71-
log.Printf("Failed to unmarshal file %s for room keys", f)
72-
return result
73-
}
74-
for room, key := range raw {
75-
result.mapChanKey.Store(room, key)
76-
result.mapKeyChan.Store(key, room)
77-
}
78-
return result
79-
}
80-
81-
func (r *RoomKeysType) Save(f string) {
82-
raw := map[string]string{}
83-
r.mapChanKey.Range(func(channel, key interface{}) bool {
84-
raw[channel.(string)] = key.(string)
85-
return true
86-
})
87-
content, err := json.Marshal(raw)
88-
if err != nil {
89-
log.Println("Failed to marshal room keys")
90-
return
91-
}
92-
if ioutil.WriteFile(f, content, 0644) != nil {
93-
log.Println("Failed to save room keys")
94-
return
95-
}
96-
}
97-
9848
// set/reset a random key for channel
9949
func (r *RoomKeysType) SetKey(channel string) (key string, err error) {
100-
if !saveInFile {
50+
if !saveInLocal {
10151
for {
10252
key = randStringRunes(48)
103-
if _, err = redisCli.Get(key).Result(); err == redis.Nil {
104-
err = redisCli.Set(channel, key, 0).Err()
53+
if _, err = r.redisCli.Get(key).Result(); err == redis.Nil {
54+
err = r.redisCli.Set(channel, key, 0).Err()
10555
if err != nil {
10656
return
10757
}
10858

109-
err = redisCli.Set(key, channel, 0).Err()
59+
err = r.redisCli.Set(key, channel, 0).Err()
11060
return
11161
} else if err != nil {
11262
return
@@ -116,9 +66,9 @@ func (r *RoomKeysType) SetKey(channel string) (key string, err error) {
11666

11767
for {
11868
key = randStringRunes(48)
119-
if _, found := r.mapKeyChan.Load(key); !found {
120-
r.mapChanKey.Store(channel, key)
121-
r.mapKeyChan.Store(key, channel)
69+
if _, found := r.localCache.Get(key); !found {
70+
r.localCache.SetDefault(channel, key)
71+
r.localCache.SetDefault(key, channel)
12272
break
12373
}
12474
}
@@ -127,8 +77,8 @@ func (r *RoomKeysType) SetKey(channel string) (key string, err error) {
12777
}
12878

12979
func (r *RoomKeysType) GetKey(channel string) (newKey string, err error) {
130-
if !saveInFile {
131-
if newKey, err = redisCli.Get(channel).Result(); err == redis.Nil {
80+
if !saveInLocal {
81+
if newKey, err = r.redisCli.Get(channel).Result(); err == redis.Nil {
13282
newKey, err = r.SetKey(channel)
13383
log.Printf("[KEY] new channel [%s]: %s", channel, newKey)
13484
return
@@ -139,7 +89,7 @@ func (r *RoomKeysType) GetKey(channel string) (newKey string, err error) {
13989

14090
var key interface{}
14191
var found bool
142-
if key, found = r.mapChanKey.Load(channel); found {
92+
if key, found = r.localCache.Get(channel); found {
14393
return key.(string), nil
14494
}
14595
newKey, err = r.SetKey(channel)
@@ -148,11 +98,11 @@ func (r *RoomKeysType) GetKey(channel string) (newKey string, err error) {
14898
}
14999

150100
func (r *RoomKeysType) GetChannel(key string) (channel string, err error) {
151-
if !saveInFile {
152-
return redisCli.Get(key).Result()
101+
if !saveInLocal {
102+
return r.redisCli.Get(key).Result()
153103
}
154104

155-
chann, found := r.mapKeyChan.Load(key)
105+
chann, found := r.localCache.Get(key)
156106
if found {
157107
return chann.(string), nil
158108
} else {
@@ -161,28 +111,28 @@ func (r *RoomKeysType) GetChannel(key string) (channel string, err error) {
161111
}
162112

163113
func (r *RoomKeysType) DeleteChannel(channel string) bool {
164-
if !saveInFile {
165-
return redisCli.Del(channel).Err() != nil
114+
if !saveInLocal {
115+
return r.redisCli.Del(channel).Err() != nil
166116
}
167117

168-
key, ok := r.mapChanKey.Load(channel)
118+
key, ok := r.localCache.Get(channel)
169119
if ok {
170-
r.mapChanKey.Delete(channel)
171-
r.mapKeyChan.Delete(key)
120+
r.localCache.Delete(channel)
121+
r.localCache.Delete(key.(string))
172122
return true
173123
}
174124
return false
175125
}
176126

177127
func (r *RoomKeysType) DeleteKey(key string) bool {
178-
if !saveInFile {
179-
return redisCli.Del(key).Err() != nil
128+
if !saveInLocal {
129+
return r.redisCli.Del(key).Err() != nil
180130
}
181131

182-
channel, ok := r.mapKeyChan.Load(key)
132+
channel, ok := r.localCache.Get(key)
183133
if ok {
184-
r.mapChanKey.Delete(channel)
185-
r.mapKeyChan.Delete(key)
134+
r.localCache.Delete(channel.(string))
135+
r.localCache.Delete(key)
186136
return true
187137
}
188138
return false

configure/liveconfig.go

Lines changed: 7 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,8 @@ import (
2020
}
2121
*/
2222
var (
23-
roomKeySaveFile = flag.String("KeyFile", "room_keys.json", "path to save room keys")
24-
RedisAddr = flag.String("redis_addr", "", "redis addr to save room keys ex. localhost:6379")
25-
RedisPwd = flag.String("redis_pwd", "", "redis password")
23+
redisAddr = flag.String("redis_addr", "", "redis addr to save room keys ex. localhost:6379")
24+
redisPwd = flag.String("redis_pwd", "", "redis password")
2625
)
2726

2827
type Application struct {
@@ -31,14 +30,11 @@ type Application struct {
3130
Hlson string `json:"hlson"`
3231
StaticPush []string `json:"static_push"`
3332
}
34-
3533
type JWTCfg struct {
3634
Secret string `json:"secret"`
3735
Algorithm string `json:"algorithm"`
3836
}
39-
4037
type ServerCfg struct {
41-
KeyFile string `json:"key_file"`
4238
RedisAddr string `json:"redis_addr"`
4339
RedisPwd string `json:"redis_pwd"`
4440
JWTCfg `json:"jwt"`
@@ -69,32 +65,24 @@ func LoadConfig(configfilename string) error {
6965
return nil
7066
}
7167

72-
func GetKeyFile() *string {
73-
if len(RtmpServercfg.KeyFile) > 0 {
74-
*roomKeySaveFile = RtmpServercfg.KeyFile
75-
}
76-
77-
return roomKeySaveFile
78-
}
79-
8068
func GetRedisAddr() *string {
8169
if len(RtmpServercfg.RedisAddr) > 0 {
82-
*RedisAddr = RtmpServercfg.RedisAddr
70+
*redisAddr = RtmpServercfg.RedisAddr
8371
}
8472

85-
if len(*RedisAddr) == 0 {
73+
if len(*redisAddr) == 0 {
8674
return nil
8775
}
8876

89-
return RedisAddr
77+
return redisAddr
9078
}
9179

9280
func GetRedisPwd() *string {
9381
if len(RtmpServercfg.RedisPwd) > 0 {
94-
*RedisPwd = RtmpServercfg.RedisPwd
82+
*redisPwd = RtmpServercfg.RedisPwd
9583
}
9684

97-
return RedisPwd
85+
return redisPwd
9886
}
9987

10088
func CheckAppName(appname string) bool {

go.mod

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ require (
88
github.com/go-redis/redis/v7 v7.2.0
99
github.com/gorilla/mux v1.7.4 // indirect
1010
github.com/orcaman/concurrent-map v0.0.0-20190826125027-8c72a8bb44f6
11+
github.com/patrickmn/go-cache v2.1.0+incompatible
1112
github.com/satori/go.uuid v1.2.0
1213
github.com/smartystreets/goconvey v1.6.4 // indirect
1314
github.com/stretchr/testify v1.4.0

go.sum

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ github.com/onsi/gomega v1.7.0 h1:XPnZz8VVBHjVsy1vzJmRwIcSwiUO+JFfrv/xGiigmME=
3131
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
3232
github.com/orcaman/concurrent-map v0.0.0-20190826125027-8c72a8bb44f6 h1:lNCW6THrCKBiJBpz8kbVGjC7MgdCGKwuvBgc7LoD6sw=
3333
github.com/orcaman/concurrent-map v0.0.0-20190826125027-8c72a8bb44f6/go.mod h1:Lu3tH6HLW3feq74c2GC+jIMS/K2CFcDWnWD9XkenwhI=
34+
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
35+
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
3436
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
3537
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
3638
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=

main.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ import (
77
"time"
88

99
"livego/configure"
10+
"livego/protocol/api"
1011
"livego/protocol/hls"
1112
"livego/protocol/httpflv"
12-
"livego/protocol/httpopera"
1313
"livego/protocol/rtmp"
1414
)
1515

@@ -89,20 +89,20 @@ func startHTTPFlv(stream *rtmp.RtmpStream) {
8989
}()
9090
}
9191

92-
func startHTTPOpera(stream *rtmp.RtmpStream) {
92+
func startAPI(stream *rtmp.RtmpStream) {
9393
if *operaAddr != "" {
9494
opListen, err := net.Listen("tcp", *operaAddr)
9595
if err != nil {
9696
log.Fatal(err)
9797
}
98-
opServer := httpopera.NewServer(stream, *rtmpAddr)
98+
opServer := api.NewServer(stream, *rtmpAddr)
9999
go func() {
100100
defer func() {
101101
if r := recover(); r != nil {
102-
log.Println("HTTP-Operation server panic: ", r)
102+
log.Println("HTTP-API server panic: ", r)
103103
}
104104
}()
105-
log.Println("HTTP-Operation listen On", *operaAddr)
105+
log.Println("HTTP-API listen On", *operaAddr)
106106
opServer.Serve(opListen)
107107
}()
108108
}
@@ -124,7 +124,7 @@ func main() {
124124
stream := rtmp.NewRtmpStream()
125125
hlsServer := startHls()
126126
startHTTPFlv(stream)
127-
startHTTPOpera(stream)
127+
startAPI(stream)
128128

129129
startRtmp(stream, hlsServer)
130130
//startRtmp(stream, nil)

0 commit comments

Comments
 (0)
0