douchun6221 2011-05-16 18:14
浏览 24
已采纳

注册表模式中的异步回复

I'm learning go, and I would like to explore some patterns.

I would like to build a Registry component which maintains a map of some stuff, and I want to provide a serialized access to it:

Currently I ended up with something like this:

type JobRegistry struct {
  submission chan JobRegistrySubmitRequest
  listing chan JobRegistryListRequest
}

type JobRegistrySubmitRequest struct {
  request JobSubmissionRequest
  response chan Job
}

type JobRegistryListRequest struct {
  response chan []Job
}

func NewJobRegistry() (this *JobRegistry) {
  this = &JobRegistry{make(chan JobRegistrySubmitRequest, 10), make(chan JobRegistryListRequest, 10)}

  go func() {
    jobMap := make(map[string] Job)

    for {
        select {
        case sub := <- this.submission:
            job := MakeJob(sub.request) // ....

            jobMap[job.Id] = job
            sub.response <- job.Id

        case list := <- this.listing:

            res := make([]Job, 0, 100)
            for _, v := range jobMap {
                res = append(res, v)
            }
            list.response <- res

        }

        /// case somechannel....
     }
   }()

   return
}

Basically, I encapsulate each operation inside a struct, which carries the parameters and a response channel.

Then I created helper methods for end users:

func (this *JobRegistry) List() ([]Job, os.Error) {
    res := make(chan []Job, 1)
    req := JobRegistryListRequest{res}
    this.listing <- req
    return <-res, nil // todo: handle errors like timeouts
}

I decided to use a channel for each type of request in order to be type safe.


The problem I see with this approach are:

  • A lot of boilerplate code and a lot of places to modify when some param/return type changes

  • Have to do weird things like create yet another wrapper struct in order to return errors from within the handler goroutine. (If I understood correctly there are no tuples, and no way to send multiple values in a channel, like multi-valued returns)

So, I'm wondering whether all this makes sense, or rather just get back to good old locks.

I'm sure that somebody will find some clever way out using channels.

  • 写回答

1条回答 默认 最新

  • duanchigeng4313 2011-05-30 15:48
    关注

    I'm not entirely sure I understand you, but I'll try answering never the less.

    You want a generic service that executes jobs sent to it. You also might want the jobs to be serializable.

    What we need is an interface that would define a generic job.

    type Job interface {
        Run()
        Serialize(io.Writer)
    }
    
    func ReadJob(r io.Reader) {...}
    
    type JobManager struct {
        jobs map[int] Job
        jobs_c chan Job      
    }
    
    func NewJobManager (mgr *JobManager) {
        mgr := &JobManager{make(map[int]Job),make(chan Job,JOB_QUEUE_SIZE)}
        for {
            j,ok := <- jobs_c
            if !ok {break}
            go j.Run()
        }
    }
    
    type IntJob struct{...}
    func (job *IntJob) GetOutChan() chan int {...}
    func (job *IntJob) Run() {...}
    func (job *IntJob) Serialize(o io.Writer) {...}
    

    Much less code, and roughly as useful.

    About signaling errors with an axillary stream, you can always use a helper function.

    type IntChanWithErr struct {
        c chan int
        errc chan os.Error
    }
    func (ch *IntChanWithErr) Next() (v int,err os.Error) {
        select {
            case v := <- ch.c // not handling closed channel
            case err := <- ch.errc
        }
        return
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号