1 回答

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個贊
好吧,您有兩個選擇,對于一些簡單的實(shí)現(xiàn),我建議將地圖上的操作分離到一個單獨(dú)的結(jié)構(gòu)中。
// Index is a shared page index
type Index struct {
access sync.Mutex
pages map[string]bool
}
// Mark reports that a site have been visited
func (i Index) Mark(name string) {
i.access.Lock()
i.pages[name] = true
i.access.Unlock()
}
// Visited returns true if a site have been visited
func (i Index) Visited(name string) bool {
i.access.Lock()
defer i.access.Unlock()
return i.pages[name]
}
然后,添加另一個結(jié)構(gòu),如下所示:
// Crawler is a web spider :D
type Crawler struct {
index Index
/* ... other important stuff like visited sites ... */
}
// Crawl looks for content
func (c *Crawler) Crawl(site string) {
// Implement your logic here
// For example:
if !c.index.Visited(site) {
c.index.Mark(site) // When marked
}
}
這樣你就可以讓事情變得清晰明了,可能會多一點(diǎn)代碼,但絕對更具可讀性。您需要像這樣實(shí)例爬蟲:
sameIndex := Index{pages: make(map[string]bool)}
asManyAsYouWant := Crawler{sameIndex, 0} // They will share sameIndex
如果您想更深入地使用高級解決方案,那么我會推薦生產(chǎn)者/消費(fèi)者架構(gòu)。
- 1 回答
- 0 關(guān)注
- 157 瀏覽
添加回答
舉報