這幾日,在項目中順手做了一個功能,讀取手機歸屬地資訊,然後插入mongodb
手機歸屬地格式
號碼 |
省份 |
城市 |
卡型 |
區號 |
130001 |
江蘇 |
常州 |
江蘇聯通 |
0519 |
代碼如下
package mainimport ("encoding/csv""encoding/json""fmt""io""labix.org/v2/mgo""os""runtime")/*初始化配置*/func init() {file, _ := os.Open("config.json")buf := make([]byte, 2048)n, _ := file.Read(buf)fmt.Println(string(buf))err := json.Unmarshal(buf[:n], &config)if err != nil {panic(err)fmt.Println(err)}}func main() {runtime.GOMAXPROCS(runtime.NumCPU())ImportPhoneInfo()}var config Config = Config{}var worker = runtime.NumCPU()//手機號碼type PhoneArea struct {Phone string "PhoneStart"Area string "Province"City string "City"PhoneType string "PhoneType"Code string "Code"}//配置type Config struct {MongodbServer stringPhoneareaFile string}/*匯入手機地理資訊*/func ImportPhoneInfo() {var chanPhoneArea = make(chan PhoneArea)// 標記完成dones := make(chan struct{}, worker)//讀取檔案資訊go addPhoneInfo(chanPhoneArea)//插入mongodbfor i := 0; i < worker; i++ {go doPhoneInfo(chanPhoneArea, dones)}//等待完成awaitForCloseResult(dones)fmt.Println("插入完畢")}/*擷取手機地理資訊*/func addPhoneInfo(chanPhoneArea chan<- PhoneArea) {file, err := os.Open(config.PhoneareaFile)if err != nil {fmt.Println("開啟檔案失敗", err)return}defer file.Close()fmt.Println("讀取手機地理資訊檔")reader := csv.NewReader(file)for {line, err := reader.Read()if err == io.EOF {close(chanPhoneArea)fmt.Println("手機地理資訊檔讀取完畢")break} else if err != nil {close(chanPhoneArea)fmt.Println("Error:", err)break}phonearea := PhoneArea{line[0], line[1], line[2], line[3], line[4]}chanPhoneArea <- phonearea}}/*插入資訊到mongodb*/func doPhoneInfo(chanPhoneArea <-chan PhoneArea, dones chan<- struct{}) {//開啟loop個協程session, err := mgo.Dial(config.MongodbServer)if err != nil {fmt.Println("錯誤")panic(err)return}defer session.Close()c := session.DB("Test").C("PhoneAreaInfo")for phonearea := range chanPhoneArea {fmt.Println("插入:", phonearea)c.Insert(&phonearea)}dones <- struct{}{}}func awaitForCloseResult(dones <-chan struct{}) {for {<-donesworker--if worker <= 0 {return}}}
設定檔config.json
{"MongodbServer" : "127.0.0.1","PhoneareaFile" : "phonearea.txt"}
手機地理資訊 phonearea.txt
號碼,省份,城市,卡型,區號1300000,北京,北京,北京聯通GSM卡,0101300001,江蘇,常州,江蘇聯通如意通卡,05191300006,江蘇,南京,江蘇聯通GSM卡,0251300010,北京,北京,北京聯通GSM卡,0101300011,北京,北京,北京聯通GSM卡,0101300012,天津,天津,天津聯通GSM卡,0221300013,天津,天津,天津聯通GSM卡,0221300014,天津,天津,天津聯通GSM卡,0221300015,山東,淄博,山東聯通GSM卡,05331300016,山東,煙台,山東聯通GSM卡,05351300017,山東,濟南,山東聯通GSM卡,05311300018,天津,天津,天津聯通GSM卡,0221300019,天津,天津,天津聯通GSM卡,0221300020,上海,上海,上海聯通GSM卡,0211300021,上海,上海,上海聯通GSM卡,0211300022,上海,上海,上海聯通GSM卡,0211300023,上海,上海,上海聯通GSM卡,0211300024,上海,上海,上海聯通GSM卡,0211300025,江蘇,南京,江蘇聯通GSM卡,0251300026,江蘇,南京,江蘇聯通GSM卡,025