★ 题目
https://tour.go-zh.org/concurrency/10
练习: Web 爬虫
在这个练习中,我们将会使用 Go 的并发特性来并行化一个 Web 爬虫。
修改Crawl
函数来并行地抓取 URL,并且保证不重复。
提示:你可以用一个 map 来缓存已经获取的 URL,但是要注意 map 本身并不是并发安全的!
★ 思路
需要解决的问题:
-
并行抓取,采用
WaitGroup
来管理多个线程,就像 Java 中的多线程,采用 Thread 的 join() 来等待所有线程执行结束。 -
不重复抓取 url,采用
map[string]bool
来接记录 url 是否已经被抓取过,由于 map 不是线程安全的,所以在操作 map 的时候,需要加锁,操作完 map,释放锁。
★ 代码
注:我的代码中用到了 WaitGroup
,WaitGroup
可以参考:https://golang.google.cn/pkg/sync/#example_WaitGroup
package main
import (
"fmt"
"sync"
)
var urlmap map[string]bool
var mux sync.Mutex
var wg sync.WaitGroup
type Fetcher interface {
// Fetch 返回 URL 的 body 内容,并且将在这个页面上找到的 URL 放到一个 slice 中。
Fetch(url string) (body string, urls []string, err error)
}
// Crawl 使用 fetcher 从某个 URL 开始递归的爬取页面,直到达到最大深度。
func Crawl(url string, depth int, fetcher Fetcher) {
defer wg.Done()
mux.Lock()
if exist := urlmap[url]; !exist {
//fmt.Printf("url : %s to be gotten\n", url)
urlmap[url] = true
mux.Unlock()
} else {
//fmt.Printf("return\n")
mux.Unlock()
return
}
if depth <= 0 {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
//fmt.Printf("u: %s\n", u)
wg.Add(1)
go Crawl(u, depth-1, fetcher)
}
return
}
func main() {
urlmap = make(map[string]bool)
wg.Add(1)
Crawl("https://golang.org/", 4, fetcher)
wg.Wait()
}
// fakeFetcher 是返回若干结果的 Fetcher。
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
func (f fakeFetcher) Fetch(url string) (string, []string, error) {
if res, ok := f[url]; ok {
return res.body, res.urls, nil
}
return "", nil, fmt.Errorf("not found: %s", url)
}
// fetcher 是填充后的 fakeFetcher。
var fetcher = fakeFetcher{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
输出:
found: https://golang.org/ "The Go Programming Language"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/ "Packages"
found: https://golang.org/pkg/os/ "Package os"
found: https://golang.org/pkg/fmt/ "Package fmt"
注意: Package os 会在 Package fmt 之前,这是并行处理的结果。如果不并行,那么 Package os 会在 Package fmt 之后。
如果不用 goroutine(把 go Crawl
中的go去掉),那么结果如下:
found: https://golang.org/ "The Go Programming Language"
found: https://golang.org/pkg/ "Packages"
not found: https://golang.org/cmd/
found: https://golang.org/pkg/fmt/ "Package fmt"
found: https://golang.org/pkg/os/ "Package os"
可见 Package os 会在 Package fmt 之后。