func rabbitConnect() (*amqp.Connection, error) {
	rabbitUser := os.Getenv("RABBIT_USER")
	rabbitPassword := os.Getenv("RABBIT_PASSWORD")
	rabbitHost := os.Getenv("RABBIT_HOST")
	rabbitVHost := os.Getenv("RABBIT_VHOST")
	rabbitPort := os.Getenv("RABBIT_PORT")
	conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%s/%s", rabbitUser, rabbitPassword, rabbitHost, rabbitPort, rabbitVHost))
	return conn, err
}

func rabbitRetry(attempts int, sleep time.Duration) *amqp.Connection {
	for i := 0; i < attempts; i++ {
		if conn, err := rabbitConnect(); err == nil {
			return conn
		}
		fmt.Println("Rabbit connection failed, retrying...")
		fmt.Println("Attempt: ", i)
		fmt.Println("Sleep: ", sleep)
		time.Sleep(sleep)
		sleep *= 2
	}
	return nil
}

func main() {
	conn := rabbitRetry(10, 5*time.Second)
	defer func(conn *amqp.Connection) {
		err := conn.Close()
		failOnError(err, "Failed to close a connection")
	}(conn)
  ch, err := conn.Channel()
}package main

import (
	"fmt"
	"io"
	"log"
	"math"
	"net/http"
	"sync"
	"time"
)

func main() {
	var (
		baseInterval       int           = 2
		baseIntervalTarget int           = 100 // 10800
		retryRequestTarget int           = 300
		tick               *time.Ticker  = time.NewTicker(time.Second * time.Duration(baseInterval))
		store              []interface{} = []interface{}{}
		interval           int           = 0
		increment          int           = 0
		retryRequest       int           = 0
		release            chan bool     = make(chan bool, 1)
		untilRelease       chan bool     = make(chan bool, 1)
		untilInterval      int           = 60 // 86400
	)

	for range tick.C {
		startTime := time.Now().Second()

		fmt.Printf("\n")
		fmt.Println("TIME NOW IN SECOND: ", startTime)

		n := int(math.Floor(float64((baseInterval + startTime) / 10)))
		interval += int(n)

		store = append(store, interval)
		increment++

		distinct := Distinct(store)

		fmt.Printf("\n")
		fmt.Println("SEQUENCES DATA: ", distinct)
		fmt.Println("INCREMENT DATA: ", increment)
		fmt.Printf("\n")

		position := IndexOf(increment, distinct)

		if position != -1 {
			retryRequest++
			HttpRequest(release)

			fmt.Println("SEQUENCES DATA MATCH: ", true)
			fmt.Println("RETRY REQUEST: ", retryRequest)
		} else {
			fmt.Println("SEQUENCES DATA NOT MATCH: ", false)
			fmt.Println("NO RETRY REQUEST: ", 0)
		}

		sumInterval := math.Ceil(float64(Reduce(SliceInterfaceToSliceInt(distinct)) / 10))
		fmt.Printf("\n")
		log.Println("INTERVAL: ", sumInterval)

		if c := int64(sumInterval); c >= int64(baseIntervalTarget) {
			fmt.Printf("\n")
			fmt.Println("STOP BY INTERVAL: ", c)

			interval = 0
			increment = 0
			retryRequest = 0
			store = nil

			time.AfterFunc(time.Duration(time.Second*time.Duration(untilInterval)), func() {
				untilRelease <- true
			})

			<-untilRelease

		} else if c := retryRequest; c >= retryRequestTarget {
			fmt.Printf("\n")
			fmt.Println("STOP BY RETRY REQUEST: ", c)

			interval = 0
			increment = 0
			retryRequest = 0
			store = nil

			time.AfterFunc(time.Duration(time.Second*time.Duration(untilInterval)), func() {
				untilRelease <- true
			})

			<-untilRelease
		}
	}
}

func HttpRequest(release chan bool) bool {
	res, err := http.Get("https://jsonplaceholder.typicode.com/users")

	if err != nil {
		release <- true
		log.Fatal(err.Error())
	}

	defer res.Body.Close()
	bodyByte, err := io.ReadAll(res.Body)

	if err != nil {
		release <- true
		log.Fatal(err.Error())
	}

	if len(bodyByte) > 0 {
		release <- true
	}

	<-release
	return true
}

func IndexOf(element interface{}, data []interface{}) interface{} {
	for k, v := range data {
		if element == v {
			return k
		}
	}
	return -1
}

func Distinct(data []interface{}) []interface{} {
	uniqueNumbers := make(map[interface{}]bool)
	result := []interface{}{}

	for _, num := range data {
		if !uniqueNumbers[num] {
			uniqueNumbers[num] = true
			result = append(result, num)
		}
	}

	return result
}

func Reduce(data []int) int64 {
	var sum int64

	for i := 0; i < len(data); i++ {
		sum += int64(data[i])
	}

	return sum
}

func SliceInterfaceToSliceInt(data []interface{}) []int {
	numbers := []int{}
	mutex := &sync.RWMutex{}

	for _, n := range data {
		mutex.Lock()
		numbers = append(numbers, n.(int))
		mutex.Unlock()
	}

	return numbers
}

Go相关代码片段

go zip file

golang network timeout

convert string to buffer golang

go fuck yourself

bun uptrace relation

golang grpc get headers

golang aes encryption

calculate area of circle

go validator regex

consul golang

why you need channel in gorutine

golang blake2s

golang sync condition

golang synchronize

golang synchronization

go tool pprof

go tool golang

golang starvation error

starvation golang error

golang atomic

declare variable without assignment in go

block assignment variables in go

compound assignment variables in go

redis in golang

go router short cut

golang pool

golang semaphore

go back to the previous directory in cmd

golang read from a file

go retry example

Check isset data golang

example context with timeout golang

golang swtich

go channels

Convert type interface{} to Link

how to go to next conflict vimdiff

go run auto reload

compare pointers in go

go https server

go chan example

cmd go to dir

golang field binding

MustBindWith query not work gin

go xorm builder

mac check go version

"[][]byte" in go as multi dimension

how to print all values in slice in go

what is aggregation in mongodb

go lang install

go get minio

todo in golang

how to pronounce government in british

email regex pattern

Go test excute

golang validate phone number

Go read PRIVATE KEY from pem file

golang slice indexof

golang indexof

golang json ignore field

print map in golang

isoString to datetime in golang.

where in postgres database golang

go http hello world code

golang masking phone number

golang replace substring

golang uuid escape

golang connect

get local ip address golang

golang cond

golang remove characters from string

grpc gateway

go grpc protoc

golang push

go to default in switch case

golang channel handling

golang buntdb

go how to make http requests in go

retry request golang

go rabbitmq rpc failover

go new ticker