分享
Go语言实现整型自增id生成器
大雁儿 · · 18132 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
最近需要实现一个自增序列的增长功能,原来的做法是从数据库中实现自增长就可以了,可是最近用的sequel pro死活找不到从指定值开始自增长的设置,只能自己通过代码查找数据库最后一项然后加一,这样每次需要增加数据的时候都要去查找以便,很是不方便,最近看到这篇文章,获益匪浅,作者提供的程序还能直接用,哈哈哈,赶紧mark了,谢谢作者。
原文出处:https://mikespook.com/2012/06/golang-channel-%E6%9C%89%E8%B6%A3%E7%9A%84%E5%BA%94%E7%94%A8/
查看原文后会有很多意外收获呢
package main
import (
"fmt"
"time"
"strconv"
"reflect"
)
type AutoInc struct {
start, step int
queue chan int
running bool
}
func New(start, step int) (ai *AutoInc) {
ai = &AutoInc{
start: start,
step: step,
running: true,
queue: make(chan int, 4),
}
go ai.process()
return
}
func (ai *AutoInc) process() {
defer func() {recover()}()
for i := ai.start; ai.running ; i=i+ai.step {
ai.queue <- i
}
}
func (ai *AutoInc) Id() int {
return <-ai.queue
}
func (ai *AutoInc) Close() {
ai.running = false
close(ai.queue)
}
func main() {
var ai *AutoInc
ai = New(100000,1)
for{
a :=ai.Id()
time.Sleep(5*time.Second)
b :=strconv.Itoa(a)
fmt.Println(b,reflect.TypeOf(b))
}
}
部分打印结果:
100000 string
100001 string
100002 string
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信18132 次点击
下一篇:go interface
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
最近需要实现一个自增序列的增长功能,原来的做法是从数据库中实现自增长就可以了,可是最近用的sequel pro死活找不到从指定值开始自增长的设置,只能自己通过代码查找数据库最后一项然后加一,这样每次需要增加数据的时候都要去查找以便,很是不方便,最近看到这篇文章,获益匪浅,作者提供的程序还能直接用,哈哈哈,赶紧mark了,谢谢作者。
原文出处:https://mikespook.com/2012/06/golang-channel-%E6%9C%89%E8%B6%A3%E7%9A%84%E5%BA%94%E7%94%A8/
查看原文后会有很多意外收获呢
package main
import (
"fmt"
"time"
"strconv"
"reflect"
)
type AutoInc struct {
start, step int
queue chan int
running bool
}
func New(start, step int) (ai *AutoInc) {
ai = &AutoInc{
start: start,
step: step,
running: true,
queue: make(chan int, 4),
}
go ai.process()
return
}
func (ai *AutoInc) process() {
defer func() {recover()}()
for i := ai.start; ai.running ; i=i+ai.step {
ai.queue <- i
}
}
func (ai *AutoInc) Id() int {
return <-ai.queue
}
func (ai *AutoInc) Close() {
ai.running = false
close(ai.queue)
}
func main() {
var ai *AutoInc
ai = New(100000,1)
for{
a :=ai.Id()
time.Sleep(5*time.Second)
b :=strconv.Itoa(a)
fmt.Println(b,reflect.TypeOf(b))
}
}
部分打印结果:
100000 string
100001 string
100002 string