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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
11 Monitoring and Observability Tools for 2023
Learn more
  1. DZone
  2. Coding
  3. Frameworks
  4. Microservices With Spring Boot - Part 3 - Creating Currency Conversion Microservice

Microservices With Spring Boot - Part 3 - Creating Currency Conversion Microservice

Today, we'll learn how to build a currency conversion microservice as part of this tutorial on setting up a microservices architecture with Spring Boot.

Ranga Karanam user avatar by
Ranga Karanam
CORE ·
Jan. 25, 18 · Tutorial
Like (15)
Save
Tweet
Share
22.34K Views

Join the DZone community and get the full member experience.

Join For Free

let's learn the basics of microservices and microservices architectures. we will also start looking at a basic implementation of a microservice with spring boot. we will create a couple of microservices and get them to talk to each other using eureka naming server and ribbon for client side load balancing.

this is part 3 of this series. in this part, we will focus on creating the currency conversion microservice.

microservices with spring boot

  • part 1 - getting started with microservices architecture
  • part 2 - creating forex microservice
  • current part - part 3 - creating currency conversion microservice
  • part 4 - using ribbon for load balancing
  • part 5 - using eureka naming server


you will learn:

  • how to create a microservice with spring boot.
  • how to use resttemplate to execute a rest service.
  • how to use feign to execute a rest service.
  • the advantages of feign over resttemplate.

resources overview

currency conversion service (ccs) can convert a bucket of currencies into another currency. it uses the forex service to get current currency exchange values. ccs is the service consumer.

an example request and response is shown below:

get to http://localhost:8100/currency-converter/from/eur/to/inr/quantity/10000

{
  id: 10002,
  from: "eur",
  to: "inr",
  conversionmultiple: 75,
  quantity: 10000,
  totalcalculatedamount: 750000,
  port: 8000,
}

the request above is to find the value of 10000 eur in inr. the totalcalculatedamount is 750000 inr.

the diagram below shows the communication between ccs and fs.

project code structure

the following screenshot shows the structure of the project we will create.

a few details:

  • springbootmicroservicecurrencyconversionapplication.java - the spring boot application class generated with spring initializer. this class acts as the launching point for the application.
  • pom.xml - contains all the dependencies needed to build this project. we will use spring boot starter web.
  • currencyconversionbean.java - bean to hold the response that we want to send out.
  • currencyexchangeserviceproxy.java - this will be the feign proxy to call the forex service.
  • currencyconversioncontroller.java - spring rest controller exposing the currency conversion service. this will use the currencyexchangeserviceproxy to call the forex service.

tools you will need

  • maven 3.0+ is your build tool
  • your favorite ide. we use eclipse.
  • jdk 1.8+

complete maven project with code examples

our github repository has all the code examples.

bootstrapping with spring initializr

creating a microservice with spring initializr is a cake walk.

spring initializr is a great tool to bootstrap your spring boot projects.

you can create a wide variety of projects using spring initializr.

th following steps have to be done for a web services project:

  • launch spring initializr and choose the following
    • choose com.in28minutes.springboot.microservice.example.currencyconversion as group
    • choose spring-boot-microservice-currency-conversion as artifact
    • choose the following dependencies:
      • web
      • devtools
      • feign
  • click generate project.
  • import the project into eclipse. file -> import -> existing maven project.
  • do not forget to choose feign in the dependencies.

creating currencyconversionbean

this is a simple bean for creating the response.

public class currencyconversionbean {
  private long id;
  private string from;
  private string to;
  private bigdecimal conversionmultiple;
  private bigdecimal quantity;
  private bigdecimal totalcalculatedamount;
  private int port;

  public currencyconversionbean() {

  }

  public currencyconversionbean(long id, string from, string to, bigdecimal conversionmultiple, bigdecimal quantity,
      bigdecimal totalcalculatedamount, int port) {
    super();
    this.id = id;
    this.from = from;
    this.to = to;
    this.conversionmultiple = conversionmultiple;
    this.quantity = quantity;
    this.totalcalculatedamount = totalcalculatedamount;
    this.port = port;
  }


implement rest client with resttemplate

the code below shows the implementation of rest client to call the forex service and process the response. as you can see, there is a lot of code that needs to be written for making a simple service call.

@restcontroller
public class currencyconversioncontroller {

  private logger logger = loggerfactory.getlogger(this.getclass());

  @getmapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
  public currencyconversionbean convertcurrency(@pathvariable string from, @pathvariable string to,
      @pathvariable bigdecimal quantity) {

    map<string, string> urivariables = new hashmap<>();
    urivariables.put("from", from);
    urivariables.put("to", to);

    responseentity<currencyconversionbean> responseentity = new resttemplate().getforentity(
        "http://localhost:8000/currency-exchange/from/{from}/to/{to}", currencyconversionbean.class,
        urivariables);

    currencyconversionbean response = responseentity.getbody();

    return new currencyconversionbean(response.getid(), from, to, response.getconversionmultiple(), quantity,
        quantity.multiply(response.getconversionmultiple()), response.getport());
  }


configure application name and port

/spring-boot-microservice-currency-conversion-service/src/main/resources/application.properties

spring.application.name=currency-conversion-service
server.port=8100

we are assigning an application name as well as a default port of 8100 .

testing the microservice

start the spring boot application by launching springbootmicroservicecurrencyconversionapplication.java .

get to http://localhost:8100/currency-converter/from/eur/to/inr/quantity/10000

{
  id: 10002,
  from: "eur",
  to: "inr",
  conversionmultiple: 75,
  quantity: 10000,
  totalcalculatedamount: 750000,
  port: 8000,
}


creating a feign proxy

feign provide a better alternative to resttemplate to call rest api.

/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/currencyexchangeserviceproxy.java

package com.in28minutes.springboot.microservice.example.currencyconversion;

import org.springframework.cloud.netflix.feign.feignclient;
import org.springframework.cloud.netflix.ribbon.ribbonclient;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;

@feignclient(name="forex-service" url="localhost:8000")
public interface currencyexchangeserviceproxy {
  @getmapping("/currency-exchange/from/{from}/to/{to}")
  public currencyconversionbean retrieveexchangevalue
    (@pathvariable("from") string from, @pathvariable("to") string to);
}

we first define a simple proxy.

  • @feignclient(name="forex-service" url="localhost:8100") - declares that this is a feign client and the url at which forex-service is present is localhost:8100
  • @getmapping("/currency-exchange/from/{from}/to/{to}") - uri of the service we would want to consume

using feign proxy from the microservice controller

making the call using the proxy is very simple. you can see it in action in the code below. all that we had to do was to autowire the proxy and use it to call the method.

  @autowired
  private currencyexchangeserviceproxy proxy;

  @getmapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
  public currencyconversionbean convertcurrencyfeign(@pathvariable string from, @pathvariable string to,
      @pathvariable bigdecimal quantity) {

    currencyconversionbean response = proxy.retrieveexchangevalue(from, to);

    logger.info("{}", response);

    return new currencyconversionbean(response.getid(), from, to, response.getconversionmultiple(), quantity,
        quantity.multiply(response.getconversionmultiple()), response.getport());
  }


enable feign clients

before we are able to use feign, we need to enable it by using @enablefeignclients annotation on the appropriate package where the client proxies are defined.

@springbootapplication
@enablefeignclients("com.in28minutes.springboot.microservice.example.currencyconversion")
@enablediscoveryclient
public class springbootmicroservicecurrencyconversionapplication {

  public static void main(string[] args) {
    springapplication.run(springbootmicroservicecurrencyconversionapplication.class, args);
  }
}


testing the microservice using feign

get to http://localhost:8100/currency-converter-feign/from/eur/to/inr/quantity/10000

{
  id: 10002,
  from: "eur",
  to: "inr",
  conversionmultiple: 75,
  quantity: 10000,
  totalcalculatedamount: 750000,
  port: 8000,
}


summary

we have now created two microservices and established communication between them.

however, we are hardcoding the url for fs in ccs. that means when new instances of fs are launched up we have no way to distribute load between them.

in the next part, we will enable client-side load distribution using ribbon.

complete code example

/spring-boot-microservice-currency-conversion-service/pom.xml

<?xml version="1.0" encoding="utf-8"?>
<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelversion>4.0.0</modelversion>

  <groupid>com.in28minutes.springboot.microservice.example.currency-conversion</groupid>
  <artifactid>spring-boot-microservice-currency-conversion</artifactid>
  <version>0.0.1-snapshot</version>
  <packaging>jar</packaging>

  <name>spring-boot-microservice-currency-conversion</name>
  <description>microservices with spring boot and spring cloud - currency conversion service</description>

  <parent>
    <groupid>org.springframework.boot</groupid>
    <artifactid>spring-boot-starter-parent</artifactid>
    <version>2.0.0.m3</version>
    <relativepath /> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceencoding>utf-8</project.build.sourceencoding>
    <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>finchley.m2</spring-cloud.version>
  </properties>

  <dependencies>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-web</artifactid>
    </dependency>

    <dependency>
      <groupid>org.springframework.cloud</groupid>
      <artifactid>spring-cloud-starter-feign</artifactid>
    </dependency>

    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-devtools</artifactid>
      <scope>runtime</scope>
    </dependency>
    <dependency>
      <groupid>org.springframework.boot</groupid>
      <artifactid>spring-boot-starter-test</artifactid>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <dependencymanagement>
    <dependencies>
      <dependency>
        <groupid>org.springframework.cloud</groupid>
        <artifactid>spring-cloud-dependencies</artifactid>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencymanagement>

  <build>
    <plugins>
      <plugin>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-maven-plugin</artifactid>
      </plugin>
    </plugins>
  </build>

  <repositories>
    <repository>
      <id>spring-snapshots</id>
      <name>spring snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
    <repository>
      <id>spring-milestones</id>
      <name>spring milestones</name>
      <url>https://repo.spring.io/milestone</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </repository>
  </repositories>

  <pluginrepositories>
    <pluginrepository>
      <id>spring-snapshots</id>
      <name>spring snapshots</name>
      <url>https://repo.spring.io/snapshot</url>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </pluginrepository>
    <pluginrepository>
      <id>spring-milestones</id>
      <name>spring milestones</name>
      <url>https://repo.spring.io/milestone</url>
      <snapshots>
        <enabled>false</enabled>
      </snapshots>
    </pluginrepository>
  </pluginrepositories>


</project>


/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/currencyconversionbean.java

package com.in28minutes.springboot.microservice.example.currencyconversion;
import java.math.bigdecimal;

public class currencyconversionbean {
  private long id;
  private string from;
  private string to;
  private bigdecimal conversionmultiple;
  private bigdecimal quantity;
  private bigdecimal totalcalculatedamount;
  private int port;

  public currencyconversionbean() {

  }

  public currencyconversionbean(long id, string from, string to, bigdecimal conversionmultiple, bigdecimal quantity,
      bigdecimal totalcalculatedamount, int port) {
    super();
    this.id = id;
    this.from = from;
    this.to = to;
    this.conversionmultiple = conversionmultiple;
    this.quantity = quantity;
    this.totalcalculatedamount = totalcalculatedamount;
    this.port = port;
  }

  public long getid() {
    return id;
  }

  public void setid(long id) {
    this.id = id;
  }

  public string getfrom() {
    return from;
  }

  public void setfrom(string from) {
    this.from = from;
  }

  public string getto() {
    return to;
  }

  public void setto(string to) {
    this.to = to;
  }

  public bigdecimal getconversionmultiple() {
    return conversionmultiple;
  }

  public void setconversionmultiple(bigdecimal conversionmultiple) {
    this.conversionmultiple = conversionmultiple;
  }

  public bigdecimal getquantity() {
    return quantity;
  }

  public void setquantity(bigdecimal quantity) {
    this.quantity = quantity;
  }

  public bigdecimal gettotalcalculatedamount() {
    return totalcalculatedamount;
  }

  public void settotalcalculatedamount(bigdecimal totalcalculatedamount) {
    this.totalcalculatedamount = totalcalculatedamount;
  }

  public int getport() {
    return port;
  }

  public void setport(int port) {
    this.port = port;
  }

}


/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/currencyconversioncontroller.java

package com.in28minutes.springboot.microservice.example.currencyconversion;

import java.math.bigdecimal;
import java.util.hashmap;
import java.util.map;

import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.http.responseentity;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.client.resttemplate;

@restcontroller
public class currencyconversioncontroller {

  private logger logger = loggerfactory.getlogger(this.getclass());

  @autowired
  private currencyexchangeserviceproxy proxy;

  @getmapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}")
  public currencyconversionbean convertcurrency(@pathvariable string from, @pathvariable string to,
      @pathvariable bigdecimal quantity) {

    map<string, string> urivariables = new hashmap<>();
    urivariables.put("from", from);
    urivariables.put("to", to);

    responseentity<currencyconversionbean> responseentity = new resttemplate().getforentity(
        "http://localhost:8000/currency-exchange/from/{from}/to/{to}", currencyconversionbean.class,
        urivariables);

    currencyconversionbean response = responseentity.getbody();

    return new currencyconversionbean(response.getid(), from, to, response.getconversionmultiple(), quantity,
        quantity.multiply(response.getconversionmultiple()), response.getport());
  }

  @getmapping("/currency-converter-feign/from/{from}/to/{to}/quantity/{quantity}")
  public currencyconversionbean convertcurrencyfeign(@pathvariable string from, @pathvariable string to,
      @pathvariable bigdecimal quantity) {

    currencyconversionbean response = proxy.retrieveexchangevalue(from, to);

    logger.info("{}", response);

    return new currencyconversionbean(response.getid(), from, to, response.getconversionmultiple(), quantity,
        quantity.multiply(response.getconversionmultiple()), response.getport());
  }

}


/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/currencyexchangeserviceproxy.java

package com.in28minutes.springboot.microservice.example.currencyconversion;

import org.springframework.cloud.netflix.feign.feignclient;
import org.springframework.cloud.netflix.ribbon.ribbonclient;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.pathvariable;

@feignclient(name="forex-service" url="localhost:8000")
public interface currencyexchangeserviceproxy {
  @getmapping("/currency-exchange/from/{from}/to/{to}")
  public currencyconversionbean retrieveexchangevalue
    (@pathvariable("from") string from, @pathvariable("to") string to);
}


/spring-boot-microservice-currency-conversion-service/src/main/java/com/in28minutes/springboot/microservice/example/currencyconversion/springbootmicroservicecurrencyconversionapplication.java

package com.in28minutes.springboot.microservice.example.currencyconversion;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cloud.client.discovery.enablediscoveryclient;
import org.springframework.cloud.netflix.feign.enablefeignclients;

@springbootapplication
@enablefeignclients("com.in28minutes.springboot.microservice.example.currencyconversion")
public class springbootmicroservicecurrencyconversionapplication {

  public static void main(string[] args) {
    springapplication.run(springbootmicroservicecurrencyconversionapplication.class, args);
  }
}


/spring-boot-microservice-currency-conversion-service/src/main/resources/application.properties

spring.application.name=currency-conversion-service
server.port=8100


/spring-boot-microservice-currency-conversion-service/src/test/java/com/in28minutes/springboot/microservice/example/currencyconversion/springbootmicroservicecurrencyconversionapplicationtests.java

package com.in28minutes.springboot.microservice.example.currencyconversion;

import org.junit.test;
import org.junit.runner.runwith;
import org.springframework.boot.test.context.springboottest;
import org.springframework.test.context.junit4.springrunner;

@runwith(springrunner.class)
@springboottest
public class springbootmicroservicecurrencyconversionapplicationtests {

  @test
  public void contextloads() {
  }

}


Spring Framework microservice Spring Boot

Published at DZone with permission of Ranga Karanam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • How To Use Linux Containers
  • What Is Continuous Testing?
  • AWS CodeCommit and GitKraken Basics: Essential Skills for Every Developer
  • Tracking Software Architecture Decisions

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: