You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

58 lines
1.4 KiB
Go

9 months ago
package service
import (
"fmt"
"github.com/astaxie/beego/httplib"
"strconv"
"sync"
"time"
"weather/models"
)
type HttpWeatherService struct {
}
9 months ago
func SyncNmcCityAndNmcProvince() {
}
9 months ago
func (s *HttpWeatherService) GetNmcNowWeather() {
citys := models.GetNmcCityList()
fmt.Println(citys)
fmt.Println(len(citys))
9 months ago
if len(citys)==0 {
SyncNmcCityAndNmcProvince()
}
9 months ago
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都结束
}