package service import ( "fmt" "github.com/astaxie/beego/httplib" "strconv" "sync" "time" "weather/models" ) type HttpWeatherService struct { } func SyncNmcCityAndNmcProvince() { } func (s *HttpWeatherService) GetNmcNowWeather() { citys := models.GetNmcCityList() fmt.Println(citys) fmt.Println(len(citys)) if len(citys)==0 { SyncNmcCityAndNmcProvince() } var wg sync.WaitGroup for _, item := range citys { time.Sleep(time.Millisecond * 300) wg.Add(1) // 启动一个goroutine就登记+1 go func(city *models.NmcCity) { defer wg.Done() // goroutine结束就登记-1 fmt.Println(*city) timeUnix := time.Now().Unix() s := strconv.FormatInt(timeUnix, 10) url := "http://www.nmc.cn/rest/weather?stationid=" + item.Code + "&_=" + s + "000" fmt.Println(url) req := httplib.Get(url) //req.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true}) str, err := req.String() if err != nil { fmt.Println(err) } var nmcNowWeather = new(models.NmcNowWeather) now := time.Now() //获取当前时间 nmcNowWeather.Weather = str nmcNowWeather.Code = item.Code nmcNowWeather.WeatherDate = now.Format("2006-01-02") id,errInsert := models.AddNmcNowWeather(nmcNowWeather) if errInsert!=nil { println(errInsert.Error()) } fmt.Println(id) fmt.Println(str) }(item) } wg.Wait() // 等待所有登记的goroutine都结束 }