Retry重试 #
重试代码包 #
package retry
import "time"
// 定义重试结构体
type Retry struct {
Duartion []int // 重试值切片
Flag chan bool // 判断是否重试信道
Idx int // 当前正在执行统计
}
func NewRetry(dur []int) *Retry {
return &Retry{
Duartion: dur,
Flag: make(chan bool),
Idx: 0,
}
}
func (r *Retry)Attempts(fn func() bool) {
for {
//每隔几秒钟执行
dur := time.Duration(r.Duartion[r.Idx]) * time.Second
go time.AfterFunc(dur, func() {
r.Flag <- fn()
})
//如果true返回
if <- r.Flag{
return
}
//执行完返回
if r.Idx == len(r.Duartion) -1 {
return
}
r.Idx++
}
}
主程序 #
每隔1、3、5、7秒执行重试
r := retry.NewRetry([]int{1,3,5,7})
r.Attempts(func() bool {
// 可以做一些污染函数处理,资源请求等操作
// 比如net rpc stmp Dial zookeeper kafka等连接重试连接
if r.Idx == 3{
fmt.Println("成功")
return true
}
fmt.Println("失败")
return false
})
切片统计排序操作 #
切片排序代码包 #
package sort
import (
"path/filepath"
"sync"
)
type result struct {
Ext string
Num int
}
type TopFile struct {
lock sync.Mutex
list map[string]int
tops []*result
}
func NewTopFile(len int) *TopFile {
return &TopFile{
lock: sync.Mutex{},
list: make(map[string]int,len),
tops: make([]*result,0),
}
}
func (c *TopFile)Record(filename string) {
ext := filepath.Ext(filename)
if ext == "" || len(ext) == 1 {
return
}
rext := ext[1:]
c.lock.Lock()
defer c.lock.Unlock()
if _,ok := c.list[rext]; !ok {
c.list[rext] = 1
} else {
c.list[rext]++
}
}
func (c *TopFile)Get(n int) []*result {
c.sort(c.list)
if n == 0 {
return c.tops
} else {
return c.tops[:n]
}
}
func (c *TopFile)sort(lists map[string]int){
for{
key,value := c.getMax(lists)
r := &result{
Ext: key,
Num: value,
}
c.tops = append(c.tops,r)
delete(lists,key)
if len(lists) == 0 {
return
}
}
}
func (c *TopFile)getMax(lists map[string]int) (string,int) {
maxValue := 0
maxKey := ""
j := 0
l := len(lists)
for key, value := range lists {
j++
if maxValue <= value {
maxValue = value
maxKey = key
}
if j == l {
break
}
}
return maxKey,maxValue
}
主程序 #
func main() {
files := []string{"1.xls","2.doc","1.doc","12.doc","14.doc","3.doc","2.ppt","3.ppt","5.ppt"}
t := sort.NewTopFile(len(files))
for _, value := range files {
t.Record(value)
}
for _, r := range t.Get(0) {
fmt.Printf("排序扩展名%s===数量%d\n",r.Ext,r.Num)
}
}
运行结果
排序扩展名doc===数量5
排序扩展名ppt===数量3
排序扩展名xls===数量1
说明:把上面代码简单修改就能做词频统计