百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 热门文章 > 正文

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

bigegpt 2025-07-10 13:18 9 浏览

以下文章来源于Go Official Blog ,作者Go Official Blog

Introduction

agollo 是Apollo的 Golang 客户端

Apollo(阿波罗)是携程框架部门研发的分布式配置中心,能够集中化管理应用不同环境、不同集群的配置,配置修改后能够实时推送到应用端,并且具备规范的权限、流程治理等特性,适用于微服务配置管理场景。

如果在使用 golang 重构 java 的过程中,使用到了分布式配置中心 Apollo,那么最快的方式就是使用原来的配置,保持最平滑的迁移,这个时候你就需要一个 Apollo 的 golang 客户端,agollo 可以是你的一个选择。

使用指南

1.1.环境要求

  • Go 1.11+ (最好使用Go 1.12)

1.2.依赖

1.2.1.使用 go get 方式

go get -u github.com/zouyx/agollo/v3@latest

1.2.2.使用 go mod 方式

go.mod

require github.com/zouyx/agollo/v3 latest

执行

go mod tidy

import

import (    "github.com/zouyx/agollo/v3")

FAQ

  • 为什么要加+incompatible
  • go.mod不能下载agollo的解决方法

1.3.必要设置

Apollo 客户端依赖于 AppId,Environment 等环境信息来工作,所以请确保阅读下面的说明并且做正确的配置:

  • main : your application
  • app.properties (必要) : 连接服务端必要配置
  • seelog.xml(非必要)

1.3.1.配置

加载优先级:

  1. 类配置
  2. 环境变量指定配置文件
  3. 默认(app.properties)配置文件

1.3.1.1.类配置

会覆盖 app.properties中配置,在调用Start方法之前调用

readyConfig:=&AppConfig{        AppId:"test1",        Cluster:"dev1",        NamespaceName:"application1",        Ip:"localhost:8889",    }    InitCustomConfig(func() (*AppConfig, error) {        return readyConfig,nil    })

类配置 agollo 的 demo:

package mainimport (    "fmt"    "github.com/zouyx/agollo/v3"    "github.com/zouyx/agollo/v3/env/config")func InitAgolloConfig() error {    readyConfig := &config.AppConfig{        AppID:         "test",        Cluster:       "default",        NamespaceName: "application",        IP:            "localhost:8080",    }    agollo.InitCustomConfig(func() (*config.AppConfig, error) {        return readyConfig, nil    })    err := agollo.Start()    if err != nil {        fmt.Errorf("%v", err)        return err    }    return nil}func main(){    //Init Apollo    err := config.InitAgolloConfig()    if err != nil {        fmt.Errorf("初始化Apollo失败", err)        panic(err)    }    fmt.Println("初始化Apollo配置成功")    //Use your apollo key to test    value := agollo.GetStringValue("key", "")    fmt.Println(value)}

1.3.1.2.环境变量指定配置文件

Linux/Mac

export AGOLLO_CONF=/a/conf.properties

Windows

set AGOLLO_CONF=c:/a/conf.properties

配置文件内容与app.properties内容一样

1.3.1.3.文件配置 - app.properties

1.开发:请确保 app.properties 文件存在于workingdir目录下

2.打包后:请确保 app.properties 文件存在于与打包程序同级目录下,参考1.3.必要配置。

目前只支持json形式,其中字段包括:

  • appId :应用的身份信息,是从服务端获取配置的一个重要信息。
  • cluster :需要连接的集群,默认default
  • namespaceName :命名空间,默认:application(具体定义参考:namespace),多namespace使用英文逗号分割, 非key/value配置(json,properties,yml等),则配置为:namespace.文件类型。如:namespace.json
  • ip :Apollo的CONFIGSERVICE的ip,非METASERVICE地址

配置例子如下:

一般配置

{    "appId": "test",    "cluster": "dev",    "namespaceName": "application",    "ip": "localhost:8888"}

多namespace配置

{    "appId": "test",    "cluster": "dev",    "namespaceName": "application, applications1",    "ip": "localhost:8888"}

非key/value namespace配置

{    "appId": "test",    "cluster": "dev",    "namespaceName": "application.json,a.yml",    "ip": "localhost:8888"}

1.4日志组件

参考:

  • 自定义日志组件
  • 使用seelog日志组件

启动方式

  • 异步启动 agollo

场景:启动程序不依赖加载Apollo的配置。

func main() {     go agollo.Start()}
  • 同步启动 agollo(v1.2.0+)

场景:启动程序依赖加载 Apollo 的配置。例:初始化程序基础配置。

func main() {     agollo.Start()}
  • 启动 agollo - 自定义 logger 控件
func main() {     agollo.StartWithLogger(loggerInterface)}
  • 启动 agollo - 自定义 cache 控件 (v1.7.0+)
func main() {     agollo.StartWithCache(cacheInterface)}
  • 启动 agollo - 自定义各种控件 (v1.8.0+)
func main() {    agollo.SetLogger(loggerInterface)    agollo.SetCache(cacheInterface)    agollo.Start()}
  • 监听变更事件(阻塞)
func main() {    event := agollo.ListenChangeEvent()    changeEvent := <-event    bytes, _ := json.Marshal(changeEvent)    fmt.Println("event:", string(bytes))}

基本方法

  • String
agollo.GetStringValue(Key,DefaultValue)
  • Int
agollo.GetIntValue(Key,DefaultValue)
  • Float
agollo.GetFloatValue(Key,DefaultValue)
  • Bool
agollo.GetBoolValue(Key,DefaultValue)

切换namespace获取配置

  • 根据namespace获取配置
config := agollo.GetConfig(namespace)
  • String
config.GetStringValue(Key,DefaultValue)
  • Int
config.GetIntValue(Key,DefaultValue)
  • Float
config.GetFloatValue(Key,DefaultValue)
  • Bool
config.GetBoolValue(Key,DefaultValue)

自定义日志组件

复制以下代码至项目中,并在其中引用日志组件的方法进行打印 log

type DefaultLogger struct {}func (this *DefaultLogger)Debugf(format string, params ...interface{})  {}func (this *DefaultLogger)Infof(format string, params ...interface{}) {}func (this *DefaultLogger)Warnf(format string, params ...interface{}) error {    return nil}func (this *DefaultLogger)Errorf(format string, params ...interface{}) error {    return nil}func (this *DefaultLogger)Debug(v ...interface{}) {}func (this *DefaultLogger)Info(v ...interface{}){}func (this *DefaultLogger)Warn(v ...interface{}) error{    return nil}func (this *DefaultLogger)Error(v ...interface{}) error{    return nil}

启动

func main() {   agollo.SetLogger(&DefaultLogger{})   agollo.Start()}

自定义缓存组件

声明自定义缓存组件

//DefaultCache 默认缓存type DefaultCache struct {    defaultCache sync.Map}//Set 获取缓存func (d *DefaultCache)Set(key string, value []byte, expireSeconds int) (err error)  {    d.defaultCache.Store(key,value)    return nil}//EntryCount 获取实体数量func (d *DefaultCache)EntryCount() (entryCount int64){    count:=int64(0)    d.defaultCache.Range(func(key, value interface{}) bool {        count++        return true    })    return count}//Get 获取缓存func (d *DefaultCache)Get(key string) (value []byte, err error){    v, ok := d.defaultCache.Load(key)    if !ok{        return nil,errors.New("load default cache fail")    }    return v.([]byte),nil}//Range 遍历缓存func (d *DefaultCache)Range(f func(key, value interface{}) bool){    d.defaultCache.Range(f)}//Del 删除缓存func (d *DefaultCache)Del(key string) (affected bool) {    d.defaultCache.Delete(key)    return true}//Clear 清除所有缓存func (d *DefaultCache)Clear() {    d.defaultCache=sync.Map{}}//DefaultCacheFactory 构造默认缓存组件工厂类type DefaultCacheFactory struct {}//Create 创建默认缓存组件func (d *DefaultCacheFactory) Create()CacheInterface {    return &DefaultCache{}}

使用自定义缓存

agollo.SetCache(&DefaultCacheFactory{})agollo.Start()

  • 项目地址: https://github.com/zouyx/agollo

----------------------------------------------------------------------------

相关推荐

Go语言泛型-泛型约束与实践(go1.7泛型)

来源:械说在Go语言中,Go泛型-泛型约束与实践部分主要探讨如何定义和使用泛型约束(Constraints),以及如何在实际开发中利用泛型进行更灵活的编程。以下是详细内容:一、什么是泛型约束?**泛型...

golang总结(golang实战教程)

基础部分Go语言有哪些优势?1简单易学:语法简洁,减少了代码的冗余。高效并发:内置强大的goroutine和channel,使并发编程更加高效且易于管理。内存管理:拥有自动垃圾回收机制,减少内...

Go 官宣:新版 Protobuf API(go pro版本)

原文作者:JoeTsai,DamienNeil和HerbieOng原文链接:https://blog.golang.org/a-new-go-api-for-protocol-buffer...

Golang开发的一些注意事项(一)(golang入门项目)

1.channel关闭后读的问题当channel关闭之后再去读取它,虽然不会引发panic,但会直接得到零值,而且ok的值为false。packagemainimport"...

golang 托盘菜单应用及打开系统默认浏览器

之前看到一个应用,用go语言编写,说是某某程序的windows图形化客户端,体验一下发现只是一个托盘,然后托盘菜单的控制面板功能直接打开本地浏览器访问程序启动的webserver网页完成gui相关功...

golang标准库每日一库之 io/ioutil

一、核心函数概览函数作用描述替代方案(Go1.16+)ioutil.ReadFile(filename)一次性读取整个文件内容(返回[]byte)os.ReadFileioutil.WriteFi...

文件类型更改器——GoLang 中的 CLI 工具

我是如何为一项琐碎的工作任务创建一个简单的工具的,你也可以上周我开始玩GoLang,它是一种由Google制作的类C编译语言,非常轻量和快速,事实上它经常在Techempower的基准测...

Go (Golang) 中的 Channels 简介(golang channel长度和容量)

这篇文章重点介绍Channels(通道)在Go中的工作方式,以及如何在代码中使用它们。在Go中,Channels是一种编程结构,它允许我们在代码的不同部分之间移动数据,通常来自不同的goro...

Golang引入泛型:Go将Interface「」替换为“Any”

现在Go将拥有泛型:Go将Interface{}替换为“Any”,这是一个类型别名:typeany=interface{}这会引入了泛型作好准备,实际上,带有泛型的Go1.18Beta...

一文带你看懂Golang最新特性(golang2.0特性)

作者:腾讯PCG代码委员会经过十余年的迭代,Go语言逐渐成为云计算时代主流的编程语言。下到云计算基础设施,上到微服务,越来越多的流行产品使用Go语言编写。可见其影响力已经非常强大。一、Go语言发展历史...

Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移

以下文章来源于GoOfficialBlog,作者GoOfficialBlogIntroductionagollo是Apollo的Golang客户端Apollo(阿波罗)是携程框架部门研...

Golang使用grpc详解(golang gcc)

gRPC是Google开源的一种高性能、跨语言的远程过程调用(RPC)框架,它使用ProtocolBuffers作为序列化工具,支持多种编程语言,如C++,Java,Python,Go等。gR...

Etcd服务注册与发现封装实现--golang

服务注册register.gopackageregisterimport("fmt""time"etcd3"github.com/cor...

Golang:将日志以Json格式输出到Kafka

在上一篇文章中我实现了一个支持Debug、Info、Error等多个级别的日志库,并将日志写到了磁盘文件中,代码比较简单,适合练手。有兴趣的可以通过这个链接前往:https://github.com/...

如何从 PHP 过渡到 Golang?(php转golang)

我是PHP开发者,转Go两个月了吧,记录一下使用Golang怎么一步步开发新项目。本着有坑填坑,有错改错的宗旨,从零开始,开始学习。因为我司没有专门的Golang大牛,所以我也只能一步步自己去...