cubefs
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
15package bcache
16
17import (
18"net"
19"time"
20)
21
22const (
23DefaultTimeOut = 1 * time.Second
24ConnectExpireTime = 20
25)
26
27type ConnObject struct {
28c *net.Conn
29lastActive int64
30}
31
32type ConnPool struct {
33conns chan *ConnObject
34mincap int
35maxcap int
36expire int64
37target string
38}
39
40func NewConnPool(target string, mincap, maxcap int, expire int64) *ConnPool {
41p := &ConnPool{
42conns: make(chan *ConnObject, maxcap),
43mincap: mincap,
44maxcap: maxcap,
45expire: expire,
46target: target,
47}
48return p
49}
50
51func (connPool *ConnPool) Get() (c *net.Conn, err error) {
52var o *ConnObject
53for {
54select {
55case o = <-connPool.conns:
56default:
57return connPool.NewConnect(connPool.target)
58}
59if time.Now().UnixNano()-o.lastActive > connPool.expire {
60_ = (*o.c).Close()
61o = nil
62continue
63}
64return o.c, nil
65}
66}
67
68func (connPool *ConnPool) NewConnect(target string) (*net.Conn, error) {
69conn, err := net.DialTimeout("unix", target, DefaultTimeOut)
70
71return &conn, err
72}
73
74func (connPool *ConnPool) Put(c *net.Conn) {
75o := &ConnObject{
76c: c,
77lastActive: time.Now().UnixNano(),
78}
79select {
80case connPool.conns <- o:
81return
82default:
83if o.c != nil {
84(*o.c).Close()
85}
86return
87}
88}
89