使用golang不断检查api是否有数据变化
时间:2024-02-20
浏览:286
作者:佚名
怎么入门Golang编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《使用golang不断检查api是否有数据变化》,涉及到,有需要的可以收藏一下
我正在尝试轮询 api 以保留流量数据的时间序列,并在发生更改时将该数据保存到 postgres。
目前我有一个类似这样的实现
//this needs to check the api for new information every X seconds
func Poll(req *http.Request, client *http.Client) ([]byte, error) {
r := rand.New(rand.NewSource(99))
c := time.Tick(10 * time.Second)
for _ = range c {
//Download the current contents of the URL and do something with it
response, err := client.Do(req)
data, _ := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
return data, nil
// add a bit of jitter
jitter := time.Duration(r.Int31n(5000)) * time.Millisecond
time.Sleep(jitter)
}
}
func main() {
client := &http.Client{
Timeout: time.Second * 60 * 60 * 600,
}
url := "https://data-exchange-api.vicroads.vic.gov.au/bluetooth_data/links"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Ocp-Apim-Subscription-Key", "xx")
// response, err := client.Do(req)
data, err := Poll(req, client)
fmt.Println(string(data))
}
接下来我会做一个比较功能。
基本上,我正在尝试弄清楚如何确保循环首先调用查询并返回适当的值。
我认为这个实现可能不是很好,我只是不确定如何真正正确地实现它。我可以得到一些指导吗?
正确答案
您的问题呈现了一个典型的生产者/消费者场景,因为您的 poll() 函数正在生成由 main() 函数消耗的响应数据(可能是将数据保存在 postgres 中)。 使用go例程和通道可以很好地解决这个问题。
轮询工作可以在 goroutine 中完成,该 goroutine 通过通道将响应数据传递给主函数。轮询工作时也可能出现错误(响应错误或 io 错误),因此也应该将其传达给 main() 函数。
首先定义一个新类型来保存轮询数据和错误:
type pollresponse struct {
data []byte
err error
}
在poll()函数中,启动一个go例程进行轮询工作并返回一个通道以在go例程之外共享数据:
func poll(req *http.request, client *http.client) (ch chan pollresponse){
ch = make(chan pollresponse) // buffered channel is also good
go func() {
defer func() {
close(ch)
}()
r := rand.new(rand.newsource(99))
c := time.tick(10 * time.second)
for range c {
res, err := client.do(req);
pollres := pollresponse {}
if err != nil {
pollres.data, pollres.err = nil, err
ch <- pollres
break
}
pollres.data, pollres.err = io.readall(res.body)
ch <- pollres
if pollres.err != nil {
break
}
jitter := time.duration(r.int31n(5000)) * time.millisecond
time.sleep(jitter)
}
}()
return
}
最后在 main() 函数中,调用 poll() 并读取通道以获取轮询响应:
func main() {
client := &http.client{
timeout: time.second * 60 * 60 * 600,
}
url := "https://data-exchange-api.vicroads.vic.gov.au/bluetooth_data/links"
req, err := http.newrequest("get", url, nil)
if err != nil {
return
}
req.header.set("ocp-apim-subscription-key", "xx")
pollch := poll(req, client)
for item := range pollch {
if item.err == nil {
fmt.println(string(item.data)) // or save it to postgres database
}
}
}股票通道上的范围。在每次迭代中,获取数据,检查数据是否发生变化并处理数据。关键点是从循环内部处理数据,而不是从函数返回数据。
假设您有以下功能:
// proceschangeddata updates the database with new
// data from the api endpoint.
func processchangeddata(data []byte) error {
// implement save to postgress
}
使用以下函数进行轮询:
func Poll(client *http.Client) error {
url := "https://data-exchange-api.vicroads.vic.gov.au/bluetooth_data/links"
// Use NewTicker instead of Tick so we can cleanup
// ticker on return from the function.
t := time.NewTicker(10 * time.Second)
defer t.Stop()
var prev []byte
for _ = range t.C {
// Create a new request objet for each request.
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req.Header.Set("Ocp-Apim-Subscription-Key", "xx")
resp, err := client.Do(req)
if err != nil {
// Edit error handling to match application
// requirements. I return an error here. Continuing
// the loop is also an option.
return err
}
data, err := io.ReadAll(resp.Body)
// Ensure that body is closed before handling errors
// below.
resp.Body.Close()
if err != nil {
// Edit error handling to match application
// requirements. I return an error here. Continuing
// the loop is also an option.
return err
}
if resp.StatusCode != http.StatusOK {
// Edit error handling to match application
// requirements. I return an error here. Continuing
// the loop is also an option.
return fmt.Errorf("bad status %d", resp.StatusCode)
}
if bytes.Equal(data, prev) {
continue
}
prev = data
if err := processChangedData(data); err != nil {
// Edit error handling to match application
// requirements. I return an error here. Continuing
// the loop is also an option.
return err
}
}
panic("unexpected break from loop")
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
站内热门
最新文章
热门专题
