DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices
  • Spring Boot - Tracing Micro Service Logs | Log Tracing In Microservices With Spring Cloud Sleuth
  • How to Create Microservices Using Spring

Trending

  • Building a Real-Time Change Data Capture Pipeline With Debezium, Kafka, and PostgreSQL
  • Enhancing Business Decision-Making Through Advanced Data Visualization Techniques
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • The Ultimate Guide to Code Formatting: Prettier vs ESLint vs Biome
  1. DZone
  2. Coding
  3. Frameworks
  4. Introduction to Spring Cloud: Config (Part 1)

Introduction to Spring Cloud: Config (Part 1)

Working with distributed systems? Spring Cloud is probably a top pick for most devs. Let's see how to use both it and Spring Cloud Config for your projects.

By 
Mohit Sinha user avatar
Mohit Sinha
·
May. 02, 18 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
16.2K Views

Join the DZone community and get the full member experience.

Join For Free

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, and cluster state).

It helps manage the complexity involved in building a distributed system.

In this tutorial series, we'll be using some of these patterns.

Microservices

Microservices are a software development architectural style that decomposes the application into a collection of loosely coupled services.

It improves modularity, thus making the application easier to develop, test, and deploy.

It also makes the development process more efficient by parallelizing small teams to work on different services.

There are also various difficulties regarding communication between services, managing configurations, etc. in a microservice architecture.

One should go through the Twelve-Factor App Manifesto to solve many of the problems arising with a Microservice architecture.

Spring Cloud Config

Spring Cloud Config provides server- and client-side support for externalized configuration in a distributed system.

It has two components, the Config Server and the Config Client.

The Config Server is a central place to manage external properties for applications across all environments. We could also version the configuration files using Git. It exposes REST APIs for clients to connect and get the required configuration. We can also leverage Spring Profiles to manage different configuration files for different profiles (environments).

For eg: we may decide to use an embedded H2 in our local dev profile, but use PostgreSQL in our prod profile.

The Config Client binds to the Config Server and initializes Spring Environment with remote property sources.

Dependencies

We'll use Gradle to build our projects. I recommend using Spring Initializr for bootstrapping your projects.

Config Server

We'll use:

  • Spring Boot 2
  • Spring Cloud Config Server
buildscript {
    ext {
        springBootVersion = '2.0.1.RELEASE'
    }
    ...
}

ext {
    springCloudVersion = 'Finchley.M9'
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-config-server')
    ...
}


Config Client

We'll use:

  • Spring Boot 2
  • Spring Boot Actuator
  • Spring Boot Webflux
  • Spring Cloud Starter Config
buildscript {
    ext {
        springBootVersion = '2.0.1.RELEASE'
    }
    ...
}

ext {
    springCloudVersion = 'Finchley.M9'
}

dependencies {
    compile('org.springframework.boot:spring-boot-starter-actuator')
    compile('org.springframework.boot:spring-boot-starter-webflux')
    compile('org.springframework.cloud:spring-cloud-starter-config')
    ...
}


Auto-Configuration

We'll leave Spring Boot to automatically configure our application based on the dependencies added and the properties specified.

Config Server

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


We'll also have to specify the Git repository where the configurations are stored.

server.port=8888
spring.cloud.config.server.git.uri=https://github.com/mohitsinha/spring-cloud-configuration-repo


spring.cloud.config.server.git.uri specifies the Git repository where the configurations are stored.

You can also pass the user credentials to access the Repository by passing the username and password.

spring.cloud.config.server.git.username 
spring.cloud.config.server.git.password


Config Client

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


spring.application.name=library-service
spring.cloud.config.uri=http://localhost:8888


spring.application.name is used to fetch the correct configuration file from the Git repository. It's a very important property when used with Spring Cloud projects. We'll see this later in this tutorial series.

The bootstrap properties are added with higher precedence, hence they cannot be overridden by local configuration. You can read more about it here.

management.endpoints.web.exposure.include=refresh


management.endpoints.web.exposure.include=refresh exposes the refresh actuator endpoint. We'll look at it in a while.

REST API

Let's look at some of the REST APIs that are automatically created to manage and monitor these services.

Config Server

Let's look at the configuration values for the application libary-service.

curl http://localhost:8888/library-service/default

The output obtained will look like this:

{
    "name": "library-service",
    "profiles": [
        "default"
    ],
    "label": null,
    "version": "4df9520f00d65722bf79bfe5ece03c5a18c5c1f1",
    "state": null,
    "propertySources": [
        {
            "name": "https://github.com/mohitsinha/spring-cloud-configuration-repo/library-service.properties",
            "source": {
                "library.name": "Spring Developers Library"
            }
        }
    ]
}


It gives details about the Git repository for the configuration files, the configuration values, etc. Here, we can see the value for the property library.name.

Config Client

We'll add a web endpoint that will use the property library.name defined in the configuration in the Git repository.

@RestController
@RefreshScope
class LibraryController{

    @Value("${library.name}")
    private String libraryName;

    @GetMapping("/details")
    public Mono<String> details(){
        return Mono.just(libraryName);
    }
}


A Bean marked with the annotation RefreshScope will be recreated when a configuration change occurs and a RefreshScopeRefreshedEvent is triggered.

Whenever a configuration change occurs in the Git repository, we can trigger a RefreshScopeRefreshedEvent by hitting the Spring Boot Actuator Refresh endpoint. The refresh endpoint will have to be enabled.

management.endpoints.web.exposure.include=refresh

The cURL command for the Actuator Refresh endpoint:

curl -X POST 
    http://localhost:8080/actuator/refresh \
    -H 'content-type: application/json' \
    -d '{}'


This will update the configuration values on the Config Client.

We can now check the endpoint and verify if the new configuration value is being reflected or not.

curl http://localhost:8080/details

What if there are multiple instances of the Client running, and we want to refresh the configuration values in all of them?

This can be achieved by using Spring Cloud Bus. It links the nodes of a distributed system with a lightweight message broker. You can read more about it here.

Conclusion

I have tried explaining, with a simple example, how to manage externalized configurations using Spring Cloud Config. In the next tutorial, we'll look at Service Discovery.

You can find the complete example for the Config Server and Library Service on GitHub.

Spring Framework Spring Cloud Spring Boot

Published at DZone with permission of Mohit Sinha, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Distributed Tracing System (Spring Cloud Sleuth + OpenZipkin)
  • Component Tests for Spring Cloud Microservices
  • Spring Boot - Tracing Micro Service Logs | Log Tracing In Microservices With Spring Cloud Sleuth
  • How to Create Microservices Using Spring

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!