cubefs

Форк
0
88 строк · 1.8 Кб
1
// Copyright 2022 The CubeFS Authors.
2
//
3
// Licensed under the Apache License, Version 2.0 (the "License");
4
// you may not use this file except in compliance with the License.
5
// You may obtain a copy of the License at
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12
// implied. See the License for the specific language governing
13
// permissions and limitations under the License.
14

15
package bcache
16

17
import (
18
	"net"
19
	"time"
20
)
21

22
const (
23
	DefaultTimeOut    = 1 * time.Second
24
	ConnectExpireTime = 20
25
)
26

27
type ConnObject struct {
28
	c          *net.Conn
29
	lastActive int64
30
}
31

32
type ConnPool struct {
33
	conns  chan *ConnObject
34
	mincap int
35
	maxcap int
36
	expire int64
37
	target string
38
}
39

40
func NewConnPool(target string, mincap, maxcap int, expire int64) *ConnPool {
41
	p := &ConnPool{
42
		conns:  make(chan *ConnObject, maxcap),
43
		mincap: mincap,
44
		maxcap: maxcap,
45
		expire: expire,
46
		target: target,
47
	}
48
	return p
49
}
50

51
func (connPool *ConnPool) Get() (c *net.Conn, err error) {
52
	var o *ConnObject
53
	for {
54
		select {
55
		case o = <-connPool.conns:
56
		default:
57
			return connPool.NewConnect(connPool.target)
58
		}
59
		if time.Now().UnixNano()-o.lastActive > connPool.expire {
60
			_ = (*o.c).Close()
61
			o = nil
62
			continue
63
		}
64
		return o.c, nil
65
	}
66
}
67

68
func (connPool *ConnPool) NewConnect(target string) (*net.Conn, error) {
69
	conn, err := net.DialTimeout("unix", target, DefaultTimeOut)
70

71
	return &conn, err
72
}
73

74
func (connPool *ConnPool) Put(c *net.Conn) {
75
	o := &ConnObject{
76
		c:          c,
77
		lastActive: time.Now().UnixNano(),
78
	}
79
	select {
80
	case connPool.conns <- o:
81
		return
82
	default:
83
		if o.c != nil {
84
			(*o.c).Close()
85
		}
86
		return
87
	}
88
}
89

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.