github.com/zooyer/miskit@v1.0.71/utils/pool/pool_test.go (about)

     1  package pool
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"golang.org/x/crypto/ssh"
     7  	"net"
     8  	"sync"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  type client struct {
    14  	*ssh.Client
    15  }
    16  
    17  func (c *client) Ping() (err error) {
    18  	session, err := c.NewSession()
    19  	if err != nil {
    20  		return err
    21  	}
    22  	return session.Close()
    23  }
    24  
    25  func newClient(network, addr string, config *ssh.ClientConfig) (entry Entry, err error) {
    26  	c, err := ssh.Dial(network, addr, config)
    27  	if err != nil {
    28  		return
    29  	}
    30  	return &client{Client: c}, nil
    31  }
    32  
    33  func BenchmarkNew(b *testing.B) {
    34  	var (
    35  		ctx   = context.Background()
    36  		mutex sync.Mutex
    37  		count int
    38  	)
    39  
    40  	var pool *Pool
    41  	pool = New(1, 30, time.Minute, func() (entry Entry, err error) {
    42  		mutex.Lock()
    43  		defer mutex.Unlock()
    44  		count++
    45  		if count > 30 {
    46  			fmt.Println(pool.num, len(pool.entry))
    47  		}
    48  		return newClient("tcp", "127.0.0.1:22", &ssh.ClientConfig{
    49  			Config:  ssh.Config{},
    50  			User:    "zzy",
    51  			Auth:    []ssh.AuthMethod{ssh.Password("386143717")},
    52  			Timeout: time.Second * 5,
    53  			HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
    54  				return nil
    55  			},
    56  		})
    57  	})
    58  
    59  	for i := 0; i < 10; i++ {
    60  		const goroutine = 65
    61  		start := time.Now()
    62  		var wg sync.WaitGroup
    63  		wg.Add(goroutine)
    64  		for i := 0; i < goroutine; i++ {
    65  			go func() {
    66  				defer wg.Done()
    67  				for i := 0; i < 5; i++ {
    68  					entry, err := pool.Get(ctx)
    69  					if err != nil {
    70  						b.Fatal(err)
    71  					}
    72  					if err = pool.Put(entry); err != nil {
    73  						b.Log(err)
    74  					}
    75  				}
    76  			}()
    77  		}
    78  		wg.Wait()
    79  
    80  		b.Log("len:", pool.Len())
    81  		b.Log("num:", pool.num)
    82  		b.Log("count:", count)
    83  		entry, err := pool.Get(ctx)
    84  		if err != nil {
    85  			b.Fatal(err)
    86  		}
    87  		pool.Put(entry)
    88  		b.Log(time.Since(start))
    89  	}
    90  }