Code Monkey home page Code Monkey logo

ants_tranlog's Introduction

ants_tranLog

ants是一个高性能的协程池,本例用 ants 协成池实现简单的http服务端。

实用性:

  • 实现了自动调度并发的goroutine,复用goroutine
  • 定时清理过期的goroutine,进一步节省资源
  • 可作为小微服务框架

使用

写 go 并发程序的时候如果程序会启动大量的 goroutine ,势必会消耗大量的系统资源(内存,CPU),通过使用 ants,可以实例化一个协程池,复用 goroutine ,节省资源,提升性能:

//定义任务 task 接口
type ITranLogTask interface{ DoTask() }

func DoHandleInit() error {
	var err error

	if !config.HasModuleInit() {
		return errors.New("配置文件未初始化,请先初始化")
	}
	config.SetSection("pool")

	sz := config.IntDefault("poolSize", 10)
	clusterId := config.IntDefault("clusterId", 0)

	p, err = ants.NewPoolWithFunc(sz, func(i interface{}) error {
		//pool池接受task 并字处理。
		t := i.(TranLogWorker)
		t.DoTask()
		return nil
	})
	if err != nil {
		fmt.Println(err)
		return err
	} 
	IdGenerator = idManager.NewUIdGenerator(clusterId)

	return nil
}

定义task 实例

func DoHandles(w http.ResponseWriter, r *http.Request) {
	//初始化task 实例并serve到pool池
	t := &digest.TranLogTask{W: w, R: r}
	t.NodeName = "DoLogs"
	t.Id = IdGenerator.GetUint32()
	t.Wg.Add(1)
	p.Serve(t)
	t.Wg.Wait()
	t.Infof("running goroutines: %d", p.Running())
}

该架构还不错 😊

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.