Skip to content

Commit

Permalink
五一快乐,隔离一时爽,一直隔离一直爽
Browse files Browse the repository at this point in the history
  • Loading branch information
QuinnDK committed May 3, 2020
1 parent 905becd commit 8db5134
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 3 deletions.
1 change: 0 additions & 1 deletion .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

76 changes: 76 additions & 0 deletions engine/concurrentengine.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package engine

import (
"crawl/fetcher"
"fmt"
"log"
)

type Scheduler interface {
Submit(Request)

configureWorkChan(chan Request)
}

type ConcurrentEngine struct {
Scheduler Scheduler
Workcount int
}

type SimpleScheduler struct {
workerchan chan Request
}

func (s *SimpleScheduler) Submit(r Request) {

s.workerchan <- r
}

func (s *SimpleScheduler) configureWorkChan(c chan Request) {

s.workerchan = c
}

func (e *ConcurrentEngine) Run(seeds ...Request) {

in := make(chan Request)
out := make(chan ParseResult)

for i := 0; i < e.Workcount; i++ {

CreateWork(in, out)
}

for _, r := range seeds {
e.Scheduler.Submit(r)
}

}

func CreateWork(in chan Request, out chan ParseResult) {

go func() {
for {
request := <-in

result, err := worker(request)

if err != nil {
continue
}
out <- result
}
}()

}

func worker(r Request) (ParseResult, error) {
fmt.Printf("Fetching url:%s", r.Url)
body, err := fetcher.Fetch(r.Url)
if err != nil {
log.Printf("Fetching Error:%s", r.Url)
return ParseResult{}, err
}
return r.ParseFunc(body), nil

}
5 changes: 4 additions & 1 deletion engine/engine.go → engine/simpleengine.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ import (
"log"
)

func Run(seeds ...Request) {
type simpleEngine struct {
}

func (s simpleEngine) Run(seeds ...Request) {
var requests []Request
for _, e := range seeds {
requests = append(requests, e)
Expand Down
6 changes: 5 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ import (
)

func main() {
engine.Run(engine.Request{
e := engine.ConcurrentEngine{
&engine.SimpleScheduler{},
100,
}
e.Run(engine.Request{
Url: "https://book.douban.com",
ParseFunc: parse.ParseTag,
})
Expand Down

0 comments on commit 8db5134

Please sign in to comment.