开发相关工具调研
微服务开发框架
开源开发框架:
https://github.com/zeromicro/go-zero :一个带有 cli 工具的云原生 Go 微服务框架
微服务平台
服务治理、配置中心。
consul 和 etcd 都比较合适,偏应用开发可以选择 consul,偏云原生体系可以选择 etcd
1.Consul
适用于需要服务发现和健康检查的场景,特别是在构建微服务架构时。
适用于需要跨多个数据中心进行部署的场景,Consul 支持多数据中心,可以在不同地理区域中部署 Consul 集群。
2.Etcd
适用于需要强一致性数据存储的场景,Etcd 提供了高可用、强一致性的键值存储。
适用于 Kubernetes 和云原生项目的场景,Etcd 是 Kubernetes 的核心组件之一,也被广泛应用于其他云原生项目中。
适用于需要与其他云原生工具和框架集成的场景
API 网关
1.开源云原生 API 网关:Kong:https://github.com/Kong/kong 。Kong 是一个云原生、快速、可扩展的微服务 API 网关。Kong 提供了丰富的插件,用于实现认证、限流、日志记录等功能。Kong 支持多种语言,包括 Go。 2.腾讯云 API 网关:https://cloud.tencent.com/document/product/1364/89294
中间件/插件
HTTP 客户端
Go 语言的标准库 net/http 就提供了 HTTP 客户端的实现,非常方便使用。如果需要更多的功能,如超时控制、重试策略等,可以使用第三方库,如 go-resty。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| package main
import ( "io/ioutil" "net/http" )
func main() { resp, err := http.Get("http://example.com/") if err != nil { } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) }
|
MySQL 客户端
sqlx 是一个 Go 语言的库,它扩展了标准库中的 database/sql,提供了更方便的 API 和额外的功能。sqlx 的目标是提供一种简洁、安全且高性能的方式来操作 SQL 数据库
官方文档:https://jmoiron.github.io/sqlx/
安装:
go get -u github.com/jmoiron/sqlx
go get -u github.com/go-sql-driver/mysql
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| package main
import ( "fmt" "github.com/jmoiron/sqlx" _ "github.com/go-sql-driver/mysql" )
type User struct { ID int `db:"id"` Name string `db:"name"` }
func main() { dsn := "user:password@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local" db, err := sqlx.Connect("mysql", dsn) if err != nil { panic("failed to connect database") }
_, err = db.Exec("INSERT INTO users (name) VALUES (?)", "John Doe") if err != nil { panic(err) }
var user User err = db.Get(&user, "SELECT * FROM users WHERE id=?", 1) if err != nil { panic(err) } fmt.Println("User:", user.Name)
_, err = db.Exec("UPDATE users SET name=? WHERE id=?", "Jane Doe", 1) if err != nil { panic(err) }
_, err = db.Exec("DELETE FROM users WHERE id=?", 1) if err != nil { panic(err) } }
|
Redis 客户端
Go 语言中有多个 Redis 客户端库,如 go-redis 和 redigo。其中 go-redis 提供了丰富的功能和良好的性能。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| package main
import ( "fmt" "github.com/go-redis/redis" )
func main() { client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, })
pong, err := client.Ping().Result() fmt.Println(pong, err)
}
ES(Elasticsearch)客户端 Elasticsearch 官方提供了 Go 语言的客户端库,名为 go-elasticsearch。
示例代码:
package main
import ( "fmt" "github.com/elastic/go-elasticsearch/v7" )
func main() { cfg := elasticsearch.Config{ Addresses: []string{ "http://localhost:9200", }, }
es, err := elasticsearch.NewClient(cfg) if err != nil { panic(err) }
res, err := es.Info() if err != nil { panic(err) }
fmt.Println(res)
}
|
对象存储 COS 客户端
腾讯云提供了 COS(Cloud Object Storage)的 Go 语言 SDK,可以在 Go 代码中直接调用。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| package main
import ( "context" "fmt" "net/http" "net/url" "os" "time"
"github.com/tencentyun/cos-go-sdk-v5"
)
func main() { u, \_ := url.Parse("https://<bucket>.cos.<region>.myqcloud.com") b := &cos.BaseURL{BucketURL: u} c := cos.NewClient(b, &http.Client{ Transport: &cos.AuthorizationTransport{ SecretID: os.Getenv("COS_SECRETID"), SecretKey: os.Getenv("COS_SECRETKEY"), }, })
_, err := c.Bucket.Put(context.Background(), nil) if err != nil { panic(err) }
}
|
Kafka 客户端
Go 语言中有多个 Kafka 客户端库,如 sarama 和 confluent-kafka-go。sarama 是一个纯 Go 语言实现的 Kafka 客户端库,功能丰富,使用广泛。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| package main
import ( "fmt" "github.com/Shopify/sarama" )
func main() { config := sarama.NewConfig() config.Producer.Return.Successes = true producer, err := sarama.NewSyncProducer([]string{"localhost:9092"}, config) if err != nil {
} defer func() { if err := producer.Close(); err != nil {
} }()
msg := &sarama.ProducerMessage{ Topic: "test", Value: sarama.StringEncoder("Hello World"), }
partition, offset, err := producer.SendMessage(msg) if err != nil { }
fmt.Printf("Message is stored in topic(%s)/partition(%d)/offset(%d)\n", "test", partition, offset)
}
|
Faiss 客户端
Faiss 是一个 C++ 库,因此在 Go 语言中调用 Faiss 需要借助 cgo。目前没有官方的 Faiss Go 客户端,但有一些第三方库封装了 Faiss 的 C++ 接口,例如 go-faiss。以下是一个简单的 go-faiss 使用示例:
首先,确保已经安装了 Faiss 和 go-faiss。安装 Faiss 的说明可以在官方文档中找到:https://github.com/facebookresearch/faiss/blob/main/INSTALL.md
然后,安装 go-faiss:
go get -u github.com/ondralukes/go-faiss
简单的 Go 代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package main
import ( "fmt" "github.com/ondralukes/go-faiss" )
func main() {
index := faiss.NewIndexFlatL2(2)
vectors := []float32{ 1.0, 1.0, 2.0, 2.0, 3.0, 3.0, } index.Add(vectors)
query := []float32{1.1, 1.1} ids, dists := index.Search(query, 1)
fmt.Printf("Nearest vector id: %d, distance: %f\n", ids[0], dists[0])
}
|
注,这个示例仅用于演示 go-faiss 的基本用法。在实际项目中,你可能需要根据具体需求对 Faiss 的参数和功能进行更详细的配置。更多关于 go-faiss 的信息和示例可以在其 GitHub 仓库中找到:https://github.com/ondralukes/go-faiss
Chroma 客户端
Chroma 是一个高维向量相似性搜索引擎,它可以对大量高维向量进行快速、准确的相似性检索。然而,Chroma 并没有提供官方的 Go 语言客户端。但是在官方文档:中给出了开源的解决方案:https://github.com/amikos-tech/chroma-go
使用方式:
安装:
go get github.com/amikos-tech/chroma-go
引用:
import (
chroma “github.com/amikos-tech/chroma-go”
)
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| package main
import ( "fmt" "log" "os"
chroma "github.com/amikos-tech/chroma-go" openai "github.com/amikos-tech/chroma-go/openai" godotenv "github.com/joho/godotenv"
)
func main() { client := chroma.NewClient("http://localhost:8000") collectionName := "test-collection" metadata := map[string]interface{}{} err := godotenv.Load(".env") if err != nil { fmt.Printf("Error loading .env file: %s", err) return } embeddingFunction := openai.NewOpenAIEmbeddingFunction(os.Getenv("OPENAI*API_KEY")) distanceFunction := chroma.L2 *, errRest := client.Reset() if errRest != nil { log.Fatalf("Error resetting database: %s \n", errRest.Error()) } col, err := client.CreateCollection(collectionName, metadata, true, embeddingFunction, distanceFunction) if err != nil { fmt.Printf("Error create collection: %s \n", err.Error()) return } documents := []string{ "This is a document about cats. Cats are great.", "this is a document about dogs. Dogs are great.", } ids := []string{ "ID1", "ID2", }
metadatas := []map[string]interface{}{ {"key1": "value1"}, {"key2": "value2"}, } _, addError := col.Add(nil, metadatas, documents, ids) if addError != nil { log.Fatalf("Error adding documents: %s \n", addError) } countDocs, qrerr := col.Count() if qrerr != nil { log.Fatalf("Error counting documents: %s \n", qrerr) } fmt.Printf("countDocs: %v\n", countDocs) qr, qrerr := col.Query([]string{"I love dogs"}, 5, nil, nil, nil) if qrerr != nil { log.Fatalf("Error querying documents: %s \n", qrerr) } fmt.Printf("qr: %v\n", qr.Documents[0][0])
}
|
LLM 客户端(大语言模型客户端)
不同大模型的接入方式可能会有区别,所以需要参考大模型提供的官方文档。不过一般都是提供的 http api。具体模型的使用参考下面的例子。
清华大学 ChatGLM2-6B 模型
https://github.com/THUDM/ChatGLM2-6B
参考官方文档部署好模型后,用 api 的模式运行
python api.py
使用 api 的方式调用大模型:
curl -X POST “http://127.0.0.1:8000“
-H ‘Content-Type: application/json’
-d ‘{“prompt”: “你好”, “history”: []}’
返回为:
1 2 3 4 5 6 7 8 9 10 11
| { "response": "你好 👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。", "history": [ [ "你好", "你好👋!我是人工智能助手 ChatGLM2-6B,很高兴见到你,欢迎问我任何问题。" ] ], "status": 200, "time": "2023-03-23 21:38:40" }
|