Configuring a Spring Cloud Config Server to read configuration from a GitHub repository, using @RefreshScope
to refresh beans dynamically, and leveraging Spring Boot Actuator for monitoring and refreshing can be a powerful combination. Let’s go through a step-by-step tutorial.
Step 1: Setup GitHub Repository for Configuration
- Create a GitHub Repository:
- Create a new GitHub repository to store your configuration files. Let’s call it
config-repo
.
- Add Configuration Files:
- Add application configuration files (e.g.,
application.yml
,application.properties
) to theconfig-repo
. These files will contain the properties for your services.
Step 2: Create Spring Cloud Config Server
- Create a new Spring Boot Project:
- Use Spring Initializr to create a new Spring Boot project.
- Add dependencies:
Config Server
,Actuator
, andWeb
.
- Configure
application.properties
(orapplication.yml
):
spring.application.name=config-server
server.port=8888
spring.cloud.config.server.git.uri=https://github.com/your-username/config-repo.git
- Enable Config Server:
- Annotate the main application class with
@EnableConfigServer
.
- Run the Config Server:
- Start the Config Server. It will fetch configuration from the GitHub repository.
Step 3: Create a Sample Service
- Create a new Spring Boot Project:
- Use Spring Initializr to create a new Spring Boot project.
- Add dependencies:
Web
,Actuator
, andConfig Client
.
- Configure
bootstrap.properties
(orbootstrap.yml
):
spring.application.name=sample-service
server.port=8080
spring.cloud.config.uri=http://localhost:8888
- Create a Sample Controller:
- Create a simple REST controller with a property injected using
@Value
.
Step 4: Add @RefreshScope
- Update the Controller:
- Add
@RefreshScope
annotation to the controller to enable dynamic refresh.
Step 5: Enable Actuator Endpoints
- Configure Actuator in
application.properties
(orapplication.yml
):
management.endpoints.web.exposure.include=*
- Refresh Endpoint:
- The
actuator/refresh
endpoint can be used to trigger a refresh.
Step 6: Test the Application
- Run the Sample Service:
- Start the Sample Service.
- Access the Sample Endpoint:
- Visit
http://localhost:8080/sample
to see the initial configuration.
- Update Configuration in GitHub:
- Make changes to the configuration files in the GitHub repository.
- Trigger Refresh:
- Hit the
actuator/refresh
endpoint of the Sample Service:POST http://localhost:8080/actuator/refresh
.
- Access the Sample Endpoint Again:
- Visit
http://localhost:8080/sample
to see the updated configuration.
Congratulations! You’ve successfully set up a Spring Cloud Config Server reading configuration from a GitHub repository, used @RefreshScope
to dynamically refresh beans, and enabled Actuator for monitoring and refreshing.