Go语言YAML配置文件库,类似于spring-boot

介绍一个用Go语言编写的配置管理库,它能自动将YAML配置映射到实体中,支持单profile和多profile配置,能从环境变量、flag参数和YAML中读取配置,具备错误处理和默认值设定功能。

github.com/flyleft/gpr…

一个简单的go语言配置文件库,将YAML配置自动映射到实体中, 类似与spring-boot配置文件。 会从根实体strut遍历实体属性,如果类型为bool, string, 整型, 浮点型,map[string]interface{},[]interface{}, 则会根据tag中的profile值(不设置则为当前属性名的首字母变小写)解析YAML或flag或环境变量,并赋值; 若YAML或flag或环境变量都不存在,则使用tag中的profileDefault设置默认值; 若默认值也未设置,则返回error。默认变量优先级:环境变量 > flag参数 > YAML > profileDefault默认值, 可以通过设置envHigher未false,让flag优先级 > 环境变量。 注意:接收类型和返回类型都需要为指针类型

单profile下的使用:

eureka:
  instance:
    preferIpAddress: true
    leaseRenewalIntervalInSeconds: 10
    leaseExpirationDurationInSeconds: 30
  client:
    serviceUrl:
      defaultZone: http://localhost:8000/eureka/
    registryFetchIntervalSeconds: 10
logging:
  level:
    github.com/flyleft/consul-iris/pkg/config: info
    github.com/flyleft/consul-iris/pkg/route: debug
复制代码
type SingleEnv struct {
	Eureka  SingleEureka
	Logging map[string]interface{} `profile:"logging.level" profileDefault:"{\"github.com/flyleft/consul-iris\":\"debug\"}"`
}

type SingleEureka struct {
	PreferIpAddress                  bool   `profile:"instance.preferIpAddress"`
	LeaseRenewalIntervalInSeconds    int32  `profile:"instance.leaseRenewalIntervalInSeconds"`
	LeaseExpirationDurationInSeconds uint   `profile:"instance.leaseExpirationDurationInSeconds"`
	ServerDefaultZone                string `profile:"client.serviceUrl.defaultZone" profileDefault:"http://localhost:8000/eureka/"`
	RegistryFetchIntervalSeconds     byte   `profile:"client.registryFetchIntervalSeconds"`
}

//使用
func main()  {
	env, err := Profile(&SingleEnv{}, "test-single-profile.yml", true)
	if err != nil {
		t.Error("Profile execute error", err)
	}
	trueEnv := env.(*SingleEnv)
}
//通过环境变量覆盖配置,比如设置EUREKA_INSTANCE_LEASERENEWALINTERVALINSECONDS环境变量值覆盖eureka.instance.leaseRenewalIntervalInSeconds
复制代码

多profile下的使用:

profiles:
  active: dev # 设置生效的profile

dev:
  database:
    username: root
    password: root
  eureka:
    zone: http://localhost:8000/eureka/
    fetchInterval: 10
  logging:
    level:
      github.com/flyleft/consul-iris/pkg/config: info
      github.com/flyleft/consul-iris/pkg/route: debug


production:
  database:
    username: production
    password: production
  eureka:
    zone: http://localhost:8000/eureka/
    fetchInterval: 10
  logging:
    level:
      github.com/flyleft/consul-iris/pkg/config: info
      github.com/flyleft/consul-iris/pkg/route: debug

复制代码
type Eureka struct {
	Zone          string `profile:"zone"`
	FetchInterval int    `profile:"fetchInterval"`
}

type DataSource struct {
	Host     string `profile:"host" profileDefault:"localhost"`
	Username string `profile:"username"`
	Password string `profile:"password"`
}

type MultiEnv struct {
	DataSource DataSource `profile:"database"`
	Eureka     Eureka
	Logging    map[string]interface{} `profile:"logging.level" profileDefault:"{\"github.com/flyleft/consul-iris\":\"debug\"}"`
	Users      []interface{}          `profile:"users" profileDefault:"[\"admin\",\"test\",\"root\"]"`
}
func main()  {
	env, err := Profile(&MultiEnv{}, "test-multi-profile.yml", true)
	if err != nil {
		t.Error("Profile execute error", err)
	}
	trueEnv := env.(*MultiEnv)
}
//可通过环境变量DEV_EUREKA_ZONE覆盖eureka.zone的值
复制代码
### 共存兼容性分析 `spring-boot-starter-data-redis` 和 `redisson-spring-boot-starter` 是两个用于与 Redis 进行交互的依赖,但它们在实现方式和功能上存在显著差异。以下是关于两者共存兼容性的详细分析: #### 1. 自动配置冲突 `redisson-spring-boot-starter` 在其内部自动配置了多个与 Redis 相关的 Bean,例如 `redisTemplate`、`stringRedisTemplate` 和 `redisConnectionFactory`[^1]。而 `spring-boot-starter-data-redis` 同样会自动配置这些 Bean。如果同时引入这两个依赖,则可能会导致以下问题: - **Bean 定义冲突**:由于两者都定义了相同的 Bean(如 `redisTemplate`),Spring 容器可能会因为无法确定使用哪个 Bean 而抛出异常。 - **连接池管理混乱**:`spring-boot-starter-data-redis` 使用 Lettuce 或 Jedis 作为底层客户端,而 `redisson-spring-boot-starter` 使用 Redisson 的独立连接池。这可能导致资源浪费或配置冲突。 #### 2. 功能定位差异 - `spring-boot-starter-data-redis` 提供的是基础的 Redis 数据操作能力,适用于简单的键值存储和查询场景。 - `redisson-spring-boot-starter` 则专注于分布式锁、分布式集合等高级功能,基于 Redisson 实现[^1]。 因此,如果项目中需要同时使用基础数据操作和 Redisson 的高级特性,则可以通过以下方式进行调整以避免冲突。 #### 3. 解决方案 为了实现两者的共存,可以采取以下措施: - **禁用自动配置**:通过在 `application.yml` 或 `application.properties` 中显式禁用 `spring-boot-starter-data-redis` 的自动配置,避免与 `redisson-spring-boot-starter` 的冲突。例如: ```yaml spring: autoconfigure: exclude: org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration ``` - **独立配置 Redisson**:将 Redisson 的配置文件(如 `redisson.yaml`)单独放置,并确保其不共享连接池[^3]。这样可以避免 Redisson 的连接池与 Lettuce/Jedis 的连接池发生冲突。 - **明确区分使用场景**:在代码层面明确区分两者的使用场景。例如,对于简单的键值操作,使用 `spring-boot-starter-data-redis` 提供的 `redisTemplate`;而对于分布式锁等高级功能,则使用 Redisson 提供的相关 API。 #### 4. 示例代码 以下是一个简单的代码示例,展示如何在项目中同时使用两者并避免冲突: ```java // 使用 spring-boot-starter-data-redis 进行基础操作 @Autowired private RedisTemplate<String, String> redisTemplate; public void basicOperation() { redisTemplate.opsForValue().set("key", "value"); String value = redisTemplate.opsForValue().get("key"); System.out.println(value); } // 使用 redisson-spring-boot-starter 进行分布式锁操作 @Autowired private RLock lock; public void distributedLockOperation() { lock.lock(); try { // 执行需要加锁的操作 } finally { lock.unlock(); } } ``` ### 注意事项 - 确保在项目中对两者的使用场景进行清晰划分,避免功能重叠。 - 如果项目中主要依赖 Redisson 的高级功能,可以考虑仅引入 `redisson-spring-boot-starter`,并手动配置基础的 Redis 操作功能[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值