springboot apollo 自动刷新

本文详细介绍如何使用Apollo配置中心实现应用配置的自动刷新。包括引入依赖、配置文件设置、自定义配置类、实现自动刷新逻辑及测试用例。通过Apollo,可以实现在不重启服务的情况下动态更新配置。
部署运行你感兴趣的模型镜像

目录

1、引入依赖

2、配置文件

3、设置配置文件

4、需要自动刷新的类

5、实现自动刷新


1、引入依赖

        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-core</artifactId>
        </dependency>
        <dependency>
            <groupId>com.ctrip.framework.apollo</groupId>
            <artifactId>apollo-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-context</artifactId>
        </dependency>

2、配置文件

env:
  dev
app:
  id: common-dictionaries
apollo:
  meta: http://127.0.0.1:26008
  autoUpdateInjectedSpringProperties: true
  bootstrap:
    enabled: true
    namespaces: application,jdbc,redis

3、设置配置文件

redis.single.host = 127.0.0.1
redis.single.database = 101
redis.single.testOnBorrow = true
redis.single.testOnReturn = true

4、需要自动刷新的类

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.cloud.context.config.annotation.RefreshScope;

/**
 * 单机模式redis配置信息
 */
@Data
@RefreshScope
@Configuration
public class RedisSingleProperties {


    /**
     * 连接地址
     */
    @Value("${redis.single.host:#{null}}")
    private String host;

     /**
     * 端口号,默认6379
     */
     @Value("${redis.single.port:6379}")
    private int port;

    /**
     * 连接超时时间,单位毫秒,默认3秒
     */
    @Value("${redis.single.timeout:3000}")
    private int timeout;

    /**
     * 连接密码
     */
    @Value("${redis.single.password:#{null}}")
    private String password;

    /**
     * 连接的DB
     */
    @Value("${redis.single.database:0}")
    private int database;

    /**
     * 资源次最大连接数,默认8
     */
    @Value("${redis.single.maxTotal:8}")
    private int maxTotal = 8;

    /**
     * 资源池允许最大空闲连接数	,默认8
     */
    @Value("${redis.single.maxIdle:8}")
    private int maxIdle = 8;

    /**
     * 资源池确保最少空闲连接数	,默认0
     */
    @Value("${redis.single.minIdle:0}")
    private int minIdle = 0;

    /**
     * 是否开启jmx监控,可用于监控,默认为true,开启状态
     */
    @Value("${redis.single.jmxEnabled:true}")
    private boolean jmxEnabled;

    /**
     * 当资源池用尽后,调用者是否要等待。只有当为true时,下面的maxWaitMillis才会生效
     * 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
     */
    @Value("${redis.single.blockWhenExhausted:true}")
    private boolean blockWhenExhausted = true;

    /**
     * 当资源池连接用尽后,调用者的最大等待时间(单位毫秒)	-1:表示永不超时
     * 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
     */
    @Value("${redis.single.maxWaitMillis:-1}")
    private long maxWaitMillis;

    /**
     * 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
     */
    @Value("${redis.single.minEvictableIdleTimeMillis:1800000}")
    private long minEvictableIdleTimeMillis;

    /**
     * 向资源池借用连接时是否做连接有效性检查(ping),无效连接会被移除,默认false
     */
    @Value("${redis.single.testOnBorrow:false}")
    private boolean testOnBorrow = false;

    /**
     * 向资源池归还连接时是否做连接有效性测试(ping),无效连接会被移除	默认false
     */
    @Value("${redis.single.testOnReturn:false}")
    private boolean testOnReturn = false;
}

5、实现自动刷新



import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 自动刷新apollo配置
 */
@Slf4j
@Component
public class ApolloConfigChanged implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Resource
    private RefreshScope refreshScope;

    @ApolloConfigChangeListener(value = {"application","jdbc","redis"})
    public void onChange(ConfigChangeEvent changeEvent){
        log.info("================Apollo 自动刷新值 开始 ===========================");

        for (String changeKey : changeEvent.changedKeys()){
            ConfigChange configChange = changeEvent.getChange(changeKey);
            String oldValue = configChange.getOldValue();
            String newValue = configChange.getNewValue();
            log.info("changedKey:【{}】,oldValue=【{}】, newValue:【{}】", changeKey, oldValue, newValue);
        }

        refreshProperties(changeEvent);

        log.info("================Apollo 自动刷新值 结束 ===========================");
    }

    private void refreshProperties(ConfigChangeEvent changeEvent) {
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshScope.refreshAll();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

6、测试用例


import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 测试apollo自动刷新
 *
 */
@RefreshScope
@RestController
public class TestController {

    @Value("${application.name:applicationName}")
    private String applicationName;

    @Resource
    private RedisSingleProperties redisSingleProperties;


    @GetMapping("application")
    public String application(){
        return applicationName;
    }


    @GetMapping("redis")
    public String redis(){
        return redisSingleProperties.getHost();
    }


}

 

 

您可能感兴趣的与本文相关的镜像

EmotiVoice

EmotiVoice

AI应用

EmotiVoice是由网易有道AI算法团队开源的一块国产TTS语音合成引擎,支持中英文双语,包含2000多种不同的音色,以及特色的情感合成功能,支持合成包含快乐、兴奋、悲伤、愤怒等广泛情感的语音。

在 Spring Boot 应应用中集成 Apollo 配置中心客户端,主要需要完成以下配置步骤: ### Apollo 客户端基础配置 首先,确保在 `application.yml` 或 `application.properties` 文件中正确配置 Apollo 客户端的连接信息。以下是一个典型的 `application.yml` 配置示例: ```yaml spring: application: name: my-application profiles: active: dev apollo: meta: http://apollo-configservice-url bootstrap: enabled: true eureka: enabled: false cluster: default app: id: ${spring.application.name} env: name: ${spring.profiles.active} namespace: application ``` - `apollo.meta`: 指定 Apollo Config Service 的地址,用于获取配置信息。 - `apollo.bootstrap.enabled`: 启用 Apollo 的自动配置加载功能。 - `apollo.cluster`: 指定当前应用所属的集群名称。 - `apollo.app.id`: 设置应用的唯一标识,通常与 Spring Boot 的应用名称一致。 - `apollo.env.name`: 设置当前应用的环境名称,例如 dev、fat、uat 或 prod。 - `apollo.namespace`: 指定默认的命名空间,通常为 `application`。 ### Apollo 客户端依赖配置 在 `pom.xml` 文件中添加 Apollo 客户端的依赖项: ```xml <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-client</artifactId> <version>1.9.0</version> </dependency> <dependency> <groupId>com.ctrip.framework.apollo</groupId> <artifactId>apollo-spring-boot-starter</artifactId> <version>1.9.0</version> </dependency> ``` Apollo 会自动集成 Spring Boot 的配置管理机制,确保应用启动时能够从 Apollo 获取配置。 ### Kubernetes 环境下的 Apollo 配置 如果应用部署在 Kubernetes 环境中,需要确保 Apollo 配置中心的服务地址可以通过 Kubernetes 的服务发现机制访问。通常可以通过 Kubernetes 的 `Service` 或 `Ingress` 配置来暴露 Apollo Config Service。 在 Kubernetes 的 `Deployment` 文件中,可以将 Apollo 的配置信息以环境变量的形式注入: ```yaml env: - name: APOLLO_META value: "http://apollo-configservice" - name: APOLLO_APPID value: "my-application" - name: APOLLO_ENV value: "dev" ``` ### Apollo 本地模式配置 在开发环境中,可以启用 Apollo 的本地模式(local mode),以便在没有网络连接的情况下使用本地配置文件。在 `application.yml` 中配置如下内容: ```yaml apollo: local: enabled: true ``` 启用本地模式后,Apollo 客户端会优先从本地文件加载配置,如果本地文件不存在,则会从 Apollo 配置中心获取配置并缓存到本地。 ### 动态配置更新 Apollo 支持动态配置更新功能,可以在不重启应用的情况下实时更新配置。在 Spring Boot 中,可以通过 `@RefreshScope` 注解实现配置的动态刷新: ```java @RestController @RefreshScope public class MyController { @Value("${my.config.key}") private String configValue; @GetMapping("/config") public String getConfigValue() { return configValue; } } ``` 通过 `@RefreshScope` 注解,Spring Boot 会在配置更新时重新创建 Bean,从而确保获取最新的配置值。 ### 相关问题 1. 如何在 Spring Boot 应用中实现 Apollo 配置的动态刷新? 2. 在 Kubernetes 环境中,如何确保 Apollo 配置中心的高可用性? 3. Apollo 的本地模式适用于哪些场景?如何启用和配置? 4. 如何在 Spring Boot 应用中通过环境变量配置 Apollo 客户端参数? 5. Apollo 客户端在 Spring Boot 中是如何实现自动配置加载的?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值