1

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 9

Creating a Simple Microservice

-------------------------------

Step 1: Create a Maven project using Spring Initializr https://start.spring.io/

Step 2: Choose the Spring Boot version 2.2.0 M6 or higher version. Do not choose
the snapshot version.

Step 3: Provide the Group name. In our case om.javatpoint

Step 4: Provide the Artifact id. We have provided limits-service.


Step 5: Add the following dependencies: Spring Web, Spring Boot DevTools, Spring
Boot Actuator, Config Client.

Step 6: Click on Generate the project button. A zip file will download, extract it
into the hard disk.

Step 7: Now, open the eclipse. Import the created maven project. It takes some time
to download the required files.

Step 8: Once the project is downloaded, go to src/main/java. Open the


LimitsServiceApplication.

Step 9: Now run the LimitsServiceApplication.java as Java Application.

It started the Tomcat on port(s) 8080 (http).

Now we will add couple of services in the above project. For this we will have to
follow the following steps:

Step 1: Open application.properties file and write the following code:

spring.application.name=limits-service //name of application


Step 2: Create a class file with name LimitsConfigurationController.java in the
folder src/main/java under the package com.javatpoint.microservices.limitsservice
and write the following code:

package com.javatpoint.microservices.limitsservice;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.javatpoint.microservices.limitsservice.bean.LimitConfiguration;
@RestController
public class LimitsConfigurationController
{
@GetMapping("/limits")
public LimitConfiguration retriveLimitsFromConfigurations()
{
return new LimitConfiguration(1000, 1);
}
}
Step 3: Create a class file with name LimitConfiguration.java in the folder
src/main/java under the package com.javatpoint.microservices.limitservice.bean and
write the following code:

package com.javatpoint.microservices.limitsservice.bean;
public class LimitConfiguration
{
private int maximum;
private int minimum;
//no-argument constructor
protected LimitConfiguration()
{
}
//generating getters
public int getMaximum()
{
return maximum;
}
public int getMinimum()
{
return minimum;
}
//genetrating constructor using fields
public LimitConfiguration(int maximum, int minimum)
{
super();
this.maximum = maximum;
this.minimum = minimum;
}
}
Type the localhost:8080/limits in the browser and press enter, we get the JSON
response as output.

Output

{
maximum: 1000,
minimum: 1
}
Adding services to the application.properties
In the previous program, we will modify the code according to the requirement.

Now we call the limits-service from the application.properties file. In this file,
we are configuring a couple of values.

limits-service.minimum=99
limits-service.maximum=9999
There is a better approach in Spring Boot to read values from the configuration
using the annotation @ConfigurationProperties.

Step 1: Create a class with name Configuration.java in the folder src/main/java


under the package com.javatpoint.microservices.limitservice

Step 2: Add the annotations @Component and @ConfigurationProperties.

Step 3: Declare two variables minimum and maximum.

Step 4: If we are using the Configuration file, we need to generate getters and
setters.

The Configuration.java file look like this.

package com.javatpoint.microservices.limitsservice;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties("limits-service")
public class Configuration
{
private int maximum;
private int minimum;
public void setMaximum(int maximum)
{
this.maximum = maximum;
}
public void setMinimum(int minimum)
{
this.minimum = minimum;
}
public int getMaximum()
{
return maximum;
}
public int getMinimum()
{
return minimum;
}
}
Step 5: Now move to LimitsConfigurationController.java file and modify the code. In
this we will use Configuration.

package com.javatpoint.microservices.limitsservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.javatpoint.microservices.limitsservice.bean.LimitConfiguration;
@RestController
public class LimitsConfigurationController
{
@Autowired
private Configuration configuration;
@GetMapping("/limits")
public LimitConfiguration retriveLimitsFromConfigurations()
{
//getting values from the properties file
return new LimitConfiguration(configuration.getMaximum(),
configuration.getMinimum());
}
}
Now refresh the browser page. It shows the JSON format of the updated values which
are configured in application .properties file.

Output

{
maximum: 999,
minimum: 99
}

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
-----------------------------------------------------------------------------------
---
Setting up Spring Cloud Config Server
-----------------------------------------------------------------------------------
----
Step 1: Create a Maven project using Spring Initializr https://start.spring.io/

Step 2: Choose the Spring Boot version 2.2.0 M6 or higher version. Do not choose
the snapshot version.

Step 3: Provide the Group name. In our case, com.javatpoint.microservices.

Step 4: Provide the Artifact id. We have provided spring-cloud-config-server.

Step 5: Add the Spring Boot DevTools and Config Server dependencies.

Step 6: Click on Generate the project button. A zip file will download, extract it
in the hard disk.

Step 7: Now, open the eclipse. Import the downloaded maven project. It will
download the required files.

In the next step, we will create a simple Git repository and configure the spring
cloud config server to pick up the values from the particular Git repository. We
need to install the local Git.

Installing Git and creating a local repository


------------------------------------------------
Step 1: Download Git from https://git-scm.com/ and install it.

Step 2: Create a Git repository and store the files that we want to be able to
configure a limits-service. We will try to access them from the spring-cloud-
config-server. Open the Git bash and type the following commands:

Creating a new directory:


------------------------
mkdir git-localconfig-repo
cd git-localconfig-repo/
Initializing a new Git repository:

git init
It initializes an empty git repository.

Step 3: Now move to the spring-cloud-config-server project and add a link to the
specific folder.

Right-click on the spring-cloud-config-server project.


Click on Build Path->Configure Build Path…
Select the Source tab.
Click on Link Source and browse the folder git-localconfig-repo.
Right click on the folder-> New -> Other -> File -> Next -> Provide the file name:
limits-service-properties-> Finish.
Now write the following code in the properties file:
limits-service.minimum=8
limits-service.maximum=888
Step 4: Configure the user name and user email:

git config -global user.email abc@example.com


git config -global user.name "abc"
The command commits any file we have added with the git add command and also
commits any files we have changed since then.

git add -A
Now execute the command to commit the changes in the repository. It records or
snapshots the file permanently in the version history.

git commit -m "first commit"

We can see that a file is changed with two new instructions. These instructions are
changed in the local repository.

application.properties :
-----------------------
spring.application.name=spring-cloud-config-server
server.port=8888
spring.cloud.config.server.git.uri="C:\Users\Anubhav\git-localconfig-repo\limits-
services.properties"

-----------------------------------------------------------------------------------
-
Connect Spring Cloud Config Server to Local Git Repository
-----------------------------------------------------------------------------------
--

In this section, we are going to learn how to connect spring-cloud-config-server


to the local git repository. First, we will find the folder path.

Right-click on git-localconfig-repo -> Properties -> copy the Location label


address and paste it into the application.properties file.

Add the annotation @EnableConfigServer in the


SpringCloudConfigServerApplication.java file.

Type the following URL in the browser

localhost:8888/limits-service/default

Output

{
name: "limits-service",
-profiles: [
"default"
],
label: null,
version:"0898c54ae1deb62733728e37e4c7962f529ee9ad",
state: null,
-propertySources: [
- {
name: C:\Users\Anubhav\git-localconfig-repo\limits-service.properties",
-source: {
limits-service-minimum: "8",
limits-service-maximum: "88"
}
}
]
}

In this we have establish the connection between SprinCloudConfigServer and the Git
repository.

We can see that it displays a set of property and values. It also retrieves the
file name of the property file from where these values (minimum and maximum) are
retrieved.

The important thing about SpringCloudConfigServer is that it stores configuration


for multiple services. It can also store configuration for each of the services for
different environments.

In the above figure, there are three services CurrencyCalculationService,


CurrencyExchangeService, and LimitsService. The LimitsService has four environment
services Dev, QA, Stage, and Production. We can configure these three services in
SpringCloudConfigServer

Configuration for Multiple Environment in Git Repository


services Dev, QA, Stage, and Production. We can configure these three services in
SpringCloudConfigServer.
-----------------------------------------------------------------------------------
--
Configuration for Multiple Environment in Git Repository
-----------------------------------------------------------------------------------
--
In the spring-cloud-config-server project, we have added a link to git-localconfig-
repo, which contains the limits-service.properties file. It becomes the default
configuration for the limits-service.

However, we can overwrite them for a specific environment. To overwrite these


values, copy the limits-service.properties and paste in the folder git-localconfig-
reporename it with limits-service-dev.properties. Now update the minimum and
maximum values.

limits-service.minimum=1
limits-service.maximum=111
Again copy the same file and paste it in the same folder. Rename it with limits-
service-qa.properties. Now update the minimum and maximum values.

limits-service.minimum=2
limits-service.maximum=222
If we want to pick the default value of the maximum instead of modified value, put
a introduction-to-currency-conversion-and-currency-exchange-service symbol at the
starting of the statement. Now the second statement becomes a comment.

limits-service.minimum=1
introduction-to-currency-conversion-and-currency-exchange-servicelimits-
service.maximum=111
When we execute it, it picks up the maximum value 888 from the default properties
file instead of maximum value 111. Whenever we make the changes in the file, commit
the changes in the local repository
Now open the Git Bash and execute the following commands:

Create the directory in which we want to add files.


---------------------------------------------------
cd git-localconfig-repo
Add the files into the Git repository.

git add -A
Now check the status of the files that have to be committed.

git status

Now commit the changes

git commit -m "Dev and QA"

Now we can access the properties Dev and QA.

Type the following in the address bar of the browser.

localhost:8888/limits-service/qa
Output

{
name: "limits-service",
-profiles: [
"qa"
],
label: null,
version:"0898c54ae1deb62733728e37e4c7962f529ee9ad",
state: null,
-propertySources: [
- {
name: C:\Users\Anubhav\git-localconfig-repo\limits-service-qa.properties",
-source: {
limits-service-minimum: "2",
limits-service-maximum: "222"
}
},
-{
name: C:\Users\Anubhav\git-localconfig-repo\limits-service.properties?,
-source: {
limits-service-minimum: "8",
limits-service-maximum: "888"
}
}
]
}
We can observe that it is retrieving the property sources. These list of property
are in the list of priority. The heights priority is whatever values are configured
in the QA file.

If there is a value that is not present in the QA file, then the value from the
default file will be picked up. So whatever is in the QA file gets the highest
property.

Connect limits-service to Spring Cloud Config Server


-----------------------------------------------------
In this section, we will connect limits-service to pick up the configuration from
the spring-cloud-config-server. We do not need to configure values in the
application.properties file. Move to the limits-service project and rename the
application.properties file to bootstrap.properties. We do not need to configure
values in the bootstrap.properties. All the configuration values picked from the
spring-cloud-config-server. Specify the URI in the bootstrap.properties.

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

limits-service is the critical path of the bootstrap.properties. Based on the


application name, we are going to pick up values from the local Git repository. Now
restart the LimitsServiceApplication.java.

Fetching config from the server at http://localhost:8888


Located environment: name=limits-service, profiles=[default], label= null,
version="0898c54ae1deb62733728e37e4c7962f529ee9ad", state=null,
Configuring profiles for Limit Service
--------------------------------------
The point to understand here is that all the configuration for the limits-service
is coming from the Git repository. We did not configure anything in the limits-
service. The advantage of configuring stuff in the Git repository is that the
entire configuration of limits-service is separated from the deployment of the
limits-service. It will automatically pick up from the Git repository.

Now open the bootstrap.properties and add the dev profile into it.

spring .profile.active=dev
When we run the limits, it shows the following output:

{
maximum: 111,
minimum:1
}
If we look at the limits-service-dev.properties file, the values are fetching from
there.

Suppose we want to pick a maximum value from the limits-service.properties and


minimum value from limits-service-dev.properties then remove the maximum value from
the limits-service-dev.properties. The limits-service-dev.properties file looks
like this:

limits-service-minimum: 1
Now commit the changes by using the following commands:

git add *;
git status
git commit -m "removed configuration for maximum "

Now start the LimitsServiceApplication.java. When we start the


LimitsServiceApplication, it picks values from the SpringCloudConfigServer. We can
observe that it picks the maximum value from the limits-service.properties (default
service) that is 888 and the minimum value from the limit-service-dev.properties
that is 1. However, we have overwritten the minimum value of the default service.

Let's see what happens when we change the profile dev to qa. Open
bootstrap.properties and write qa in place of dev. The application will start and
pick up the changes. Now execute the limits.
Output

{
maximum: 222,
minimum: 2
}
These are the values that are coming from the qa environment configuration

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy