Go 每日一库之 java 转 go 遇到 Apollo?让 agollo 来平滑迁移
ztj100 2025-01-10 18:40 11 浏览 0 评论
以下文章来源于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.配置
加载优先级:
- 类配置
- 环境变量指定配置文件
- 默认(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
----------------------------------------------------------------------------
相关推荐
- Whoosh,纯python编写轻量级搜索工具
-
引言在许多应用程序中,搜索功能是至关重要的。Whoosh是一个纯Python编写的轻量级搜索引擎库,可以帮助我们快速构建搜索功能。无论是在网站、博客还是本地应用程序中,Whoosh都能提供高效的全文搜...
- 如何用Python实现二分搜索算法(python二分法查找代码)
-
如何用Python实现二分搜索算法二分搜索(BinarySearch)是一种高效的查找算法,适用于在有序数组中快速定位目标值。其核心思想是通过不断缩小搜索范围,每次将问题规模减半,时间复杂度为(O...
- 路径扫描 -- dirsearch(路径查找器怎么使用)
-
外表干净是尊重别人,内心干净是尊重自己,干净,在今天这个时代,应该是一种极高的赞美和珍贵。。。----网易云热评一、软件介绍Dirsearch是一种命令行工具,可以强制获取web服务器中的目录和文件...
- 78行Python代码帮你复现微信撤回消息!
-
来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。...
- 从零开始学习 Python!2《进阶知识》 Python进阶之路
-
欢迎来到Python学习的进阶篇章!如果你说已经掌握了基础语法,那么这篇就是你开启高手之路的大门。我们将一起探讨面向对象编程...
- 白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件
-
一、背景介绍...
- Python之txt数据预定替换word预定义定位标记生成word报告(四)
-
续接Python之txt数据预定替换word预定义定位标记生成word报告(一)https://mp.toutiao.com/profile_v4/graphic/preview?pgc_id=748...
- Python——字符串和正则表达式中的反斜杠('\')问题详解
-
在本篇文章里小编给大家整理的是关于Python字符串和正则表达式中的反斜杠('\')问题以及相关知识点,有需要的朋友们可以学习下。在Python普通字符串中在Python中,我们用'\'来转义某些普通...
- Python re模块:正则表达式综合指南
-
Python...
- python之re模块(python re模块sub)
-
re模块一.re模块的介绍1.什么是正则表达式"定义:正则表达式是一种对字符和特殊字符操作的一种逻辑公式,从特定的字符中,用正则表达字符来过滤的逻辑。(也是一种文本模式;)2、正则表达式可以帮助我们...
- MySQL、PostgreSQL、SQL Server 数据库导入导出实操全解
-
在数字化时代,数据是关键资产,数据库的导入导出操作则是连接数据与应用场景的桥梁。以下是常见数据库导入导出的实用方法及代码,包含更多细节和特殊情况处理,助你应对各种实际场景。一、MySQL数据库...
- Zabbix监控系统系列之六:监控 mysql
-
zabbix监控mysql1、监控规划在创建监控项之前要尽量考虑清楚要监控什么,怎么监控,监控数据如何存储,监控数据如何展现,如何处理报警等。要进行监控的系统规划需要对Zabbix很了解,这里只是...
- mysql系列之一文详解Navicat工具的使用(二)
-
本章内容是系列内容的第二部分,主要介绍Navicat工具的使用。若查看第一部分请见:...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Whoosh,纯python编写轻量级搜索工具
- 如何用Python实现二分搜索算法(python二分法查找代码)
- 路径扫描 -- dirsearch(路径查找器怎么使用)
- 78行Python代码帮你复现微信撤回消息!
- 从零开始学习 Python!2《进阶知识》 Python进阶之路
- 白帽黑客如何通过dirsearch脚本工具扫描和收集网站敏感文件
- Python之txt数据预定替换word预定义定位标记生成word报告(四)
- 假期苦短,我用Python!这有个自动回复拜年信息的小程序
- Python——字符串和正则表达式中的反斜杠('\')问题详解
- Python re模块:正则表达式综合指南
- 标签列表
-
- idea eval reset (50)
- vue dispatch (70)
- update canceled (42)
- order by asc (53)
- spring gateway (67)
- 简单代码编程 贪吃蛇 (40)
- transforms.resize (33)
- redisson trylock (35)
- 卸载node (35)
- np.reshape (33)
- torch.arange (34)
- node卸载 (33)
- npm 源 (35)
- vue3 deep (35)
- win10 ssh (35)
- exceptionininitializererror (33)
- vue foreach (34)
- idea设置编码为utf8 (35)
- vue 数组添加元素 (34)
- std find (34)
- tablefield注解用途 (35)
- python str转json (34)
- java websocket客户端 (34)
- tensor.view (34)
- java jackson (34)