19

Spring Cloud Config在Spring Cloud Task中的应用,比Web应用更简单

 3 years ago
source link: https://www.pkslow.com/archives/spring-cloud-config-for-cloud-task
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

1 前言

前面我们探索了 Spring Cloud Config 及其在 Kubernetes 中的应用,都是以常驻的 Web应用 作为配置客户端的,那对于 短命Spring Cloud Task 会有什么不一样吗?

相关文件:

使用Spring Cloud Config统一管理配置,别再到处放配置文件了

Spring Cloud Config整合Spring Cloud Kubernetes,在k8s上管理配置

配置相关文件

2 区别

其实本质区别是不大的,都是配置客户端从配置服务端拉取配置信息,再应用到自己身上。但有以下几点区别让 Spring Cloud Task 更简单:

(1) Task 不是 Web 应用,生命周期短,无须刷新配置,只在开始启动时拉取配置即可;

(2) Task 是非 常驻 应用,没有端口暴露,更不用注册到服务发现中心。

基于上面区别,我们不需要 Task 作为 DiscoveryClient ,不用实现注册相关功能;也不用添加 actuator 用于刷新配置。

3 Task实现配置拉取

3.1 项目准备

除去 Spring Cloud Task 本身的依赖,只需要添加一个 Spring Cloud Config 相关的依赖即可:

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-task</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-task-core</artifactId>
</dependency>

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

启动主类没什么特别:

@SpringBootApplication
@EnableTask
public class CloudTaskWithConfigK8s {
    public static void main(String[] args) {
        SpringApplication.run(CloudTaskWithConfigK8s.class, args);
    }
}

我们实现一个 ApplicationRunner 来打印获取到的配置:

@Component
public class PkslowAppRunner implements ApplicationRunner {
    private static Logger logger = LoggerFactory.getLogger(PkslowAppRunner.class);

    @Value("${pkslow.age:0}")
    private Integer age;

    @Value("${pkslow.email:null}")
    private String email;

    @Value("${pkslow.webSite:null}")
    private String webSite;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("running for pkslow task...");
        logger.info("pkslow age: {}", age);
        logger.info("pkslow email: {}", email);
        logger.info("pkslow webSite: {}", webSite);
    }
}

配置文件 bootstrap.properties 内部如下:

spring.application.name=config-client-cloud-task-k8s
spring.profiles.active=default
spring.cloud.config.label=master

spring.cloud.config.uri=http://config-server-k8s:8888

logging.level.root=debug

这个配置文件决定了应用从哪里读配置、如何读取配置、读取怎样的配置。

准备好后,打一个 Docker 镜像即可。

3.2 启动与验证

Spring Cloud Data Flow 平台注册 AppTask ,并启动:

aeIZ7nM.png!mobile

执行成功后,查看日志:

UVbQ7bJ.png!mobile

已经成功从 Config Server 读取到配置了。

4 总结

Spring Cloud Task 作为配置客户端,会更加简单。

欢迎关注微信公众号< 南瓜慢说 >,将持续为你更新...

Y7z2U3.png!mobile


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK