登录
首页 >  Golang >  Go问答

实现搜索功能的方法

来源:stackoverflow

时间:2024-03-03 19:54:19 214浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《实现搜索功能的方法》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我尝试开发一个可以同时从多个复制数据库读取数据的程序。它必须接受最先到达的响应。所以tsk就是实现query函数。我尝试了 select,但程序给出了错误,我认为我走错了方向。你能告诉我如何正确地实现这个程序吗?

package main

import (
    "fmt"
    "time"
)

type Conn interface {
    DoQuery(query string) Result
}

type Result struct {
    Query    string
    ConnName string
}

type Conn1 struct{}
type Conn2 struct{}
type Conn3 struct{}

func (c Conn1) DoQuery(query string) Result {
    time.Sleep(1 * time.Second)
    return Result{Query: query, ConnName: "Conn1"}
}

func (c Conn2) DoQuery(query string) Result {
    time.Sleep(2 * time.Second)
    return Result{Query: query, ConnName: "Conn2"}
}

func (c Conn3) DoQuery(query string) Result {
    time.Sleep(3 * time.Second)
    return Result{Query: query, ConnName: "Conn3"}
}

func query(conns []Conn, query string) Result {
    // <- here is the beginning of code that I implemented
    ch1 := make(chan Conn1)
    ch2 := make(chan Conn2)
    ch3 := make(chan Conn3)

    select {
    case one := <-ch1:
        return one.DoQuery("First query")
    case two := <-ch2:
        return two.DoQuery("Second query")
    case three := <-ch3:
        return three.DoQuery("Third query")
    }
    // -> here is the end of code
}

func main() {
    conns := make([]Conn, 3)
    conns[0] = Conn1{}
    conns[1] = Conn2{}
    conns[2] = Conn3{}
    res := query(conns, "select * from users")
    fmt.Println(res)
}

正确答案


在 goroutine 中运行每个查询并将每个查询的结果发送到单个通道。在主 goroutine 中的通道上接收以获取第一个结果。请参阅评论以获取更多信息。

func query(conns []Conn, query string) Result {
    // Create the channel to receive the first result. The capacity
    // len(conns)-1 ensures that all goroutines can send a value to the
    // channel and exit.
    ch := make(chan Result, len(conns)-1)

    // Start a goroutine to query on each connection. 
    // https://go.dev/doc/faq#closures_and_goroutines explains
    // why conn is passed as an argument.
    for _, conn := range conns {
        go func(conn Conn) {
            ch <- conn.DoQuery(query)
        }(conn)
    }

    // Wait for the the first result and return it.
    return <-ch
}

Run an example on the playground

今天关于《实现搜索功能的方法》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>