Microservices mit Spring Boot. Teil 3. Erstellen eines Mikrodienstes zur Währungsumrechnung

Dies ist der dritte Teil einer Artikelserie über die Grundlagen von Microservice-Architekturen, in der Sie lernen, wie Sie einen Microservice für die Währungsumrechnung erstellen.

In dieser Artikelserie werden Sie mit dem Konzept von Microservices vertraut gemacht und erfahren, wie Sie mit Spring Boot und Spring Cloud Microservices erstellen.

In diesem Handbuch lernen Sie die Grundlagen der Mikroservice-Architekturen kennen. Wir werden uns auch mit der grundlegenden Implementierung von Mikroservices mit Spring Boot befassen.

Wir werden ein Paar von Mikrodiensten erstellen und diese über die Eureka-Nameserver (Eureka Naming Server) und die Ribbon-Nameserver miteinander kommunizieren lassen, um die Belastung auf der Clientseite auszugleichen.

Dieser Artikel ist Teil der Spring Boot Microservices-Reihe:


Du wirst lernen


  • So erstellen Sie einen Microservice mit Spring Boot.
  • Verwendung von RestTemplate zum Erstellen eines REST-Service.
  • So erstellen Sie mit Feign einen REST-Service.
  • Vorteile von Feign gegenüber RestTemplate.

Ressourcenübersicht


Der Währungsumrechnungsdienst (CCS) kann viele Währungen in eine andere Währung umrechnen. Es verwendet den Forex-Dienst, um die aktuellen Währungsumrechnungswerte abzurufen. CCS ist ein Konsument von Dienstleistungen.

Ein Beispiel für eine Anfrage und eine Antwort ist unten dargestellt:

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, } 

Mit der obigen Anfrage können Sie den Wert von 10.000 Euro in indischen Rupien ermitteln.
TotalCalculatedAmount beträgt 750.000 INR. Das folgende Diagramm zeigt die Beziehung zwischen CCS und FS.



Struktur des Projektcodes


Der folgende Screenshot zeigt die Struktur des Projekts, das wir erstellen werden.



Einige Elemente des Projekts:

  • SpringBootMicroserviceCurrencyConversionApplication.java ist die Spring Boot-Anwendungsklasse, die mit Spring Initializer erstellt wurde. Diese Klasse fungiert als Startpunkt der Anwendung.
  • pom.xml - enthält alle Abhängigkeiten, die zum Erstellen dieses Projekts erforderlich sind. Wir werden das Spring Boot Starter Web verwenden.
  • CurrencyConversionBean.java - Die Bean zum Speichern der Antwort, die gesendet werden soll.
  • CurrencyExchangeServiceProxy.java - Dies ist der Feign-Proxy zum Aufrufen des Forex-Dienstes.
  • CurrencyConversionController.java - Spring-REST-Controller, der einen Währungsumrechnungsservice bereitstellt. Mit CurrencyExchangeServiceProxy wird der Forex-Dienst aufgerufen.

Werkzeuge, die Sie brauchen


  • Maven 3.0+ - Build-Tool
  • Ihre Lieblings-IDE. Wir verwenden Eclipse.
  • JDK 1.8+

Ready Maven-Projekt mit Codebeispielen


Das Github-Repository enthält alle Codebeispiele.

Erstellen eines Projekts mit dem Spring Initializr


Das Erstellen eines Microservices mit Spring Initializr ist ein Kinderspiel.

Spring Initializr ist ein großartiges Tool zum schnellen Erstellen von Spring Boot-Projekten.

Mit Hilfe von Spring Initializr können Sie eine Vielzahl von Projekten erstellen.



Die folgenden Schritte müssen ausgeführt werden, um ein Webdienstentwicklungsprojekt zu erstellen:

1. Starten Sie Spring Initializr und geben Sie Folgendes ein:

  • Geben Sie com.in28minutes.springboot.microservice.example.currencyconversion als Gruppe ein.
  • Geben Sie spring-boot-microservice-currency-conversion als Artefakt ein.
  • Wählen Sie die folgenden Abhängigkeiten aus: Web , DevTools , Feign

2. Klicken Sie auf Projekt generieren .

3. Importieren Sie das Projekt in Eclipse: Datei -> Importieren -> Vorhandenes Maven-Projekt.

Denken Sie daran , Feign in den Abhängigkeiten aufzulisten .

CurrencyConversionBean erstellen


Dies ist eine einfache Bohne, um eine Antwort zu erstellen.

 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; } 

Implementieren eines REST-Clients mit RestTemplate


Der folgende Code demonstriert die Implementierung eines REST-Clients zum Aufrufen eines Forex-Dienstes und zum Verarbeiten einer Antwort. Wie Sie sehen, müssen Sie für einen einfachen Serviceabruf viel Code schreiben.

 @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()); } 

Konfigurieren Sie den Anwendungsnamen und den Port


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

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

Microservice-Test


Starten Sie die Spring Boot-Anwendung, indem Sie SpringBootMicroserviceCurrencyConversionApplication.java ausführen

 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, } 

Feign Proxies erstellen


Feign bietet die beste Alternative zu RestTemplate zum Aufrufen der 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); } 

Zuerst definieren wir einen einfachen Proxy:

  • @FeignClient (name = "forex-service" url = "localhost: 8100") - erklärt, dass dies ein Feign-Client ist und die URL, unter der sich der Forex-Service befindet, localhost: 8100 ist
  • @GetMapping ("/ currency-exchange / from / {from} / to / {to}") - Die URI des Dienstes, den wir verwenden möchten

Verwenden von Feign-Proxies in einem Microservice-Controller


Das Tätigen eines Anrufs über einen Proxy ist sehr einfach. Sie werden dies im folgenden Code in Aktion sehen. Alles, was wir tun mussten, war, den Proxy automatisch zu verbinden und damit die Methode aufzurufen.

 @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()); } 

Feign Clients aktivieren


Bevor wir Feign verwenden können, müssen wir es mit der Annotation @EnableFeignClients im entsprechenden Paket aktivieren, in dem die Client-Proxys definiert sind.

 @SpringBootApplication @EnableFeignClients("com.in28minutes.springboot.microservice.example.currencyconversion") @EnableDiscoveryClient public class SpringBootMicroserviceCurrencyConversionApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMicroserviceCurrencyConversionApplication.class, args); } } 

Testen eines Microservice mit 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, } 

Zusammenfassung


Wir haben zwei Microservices erstellt und eine Verbindung zwischen ihnen hergestellt.



Wir haben die URL für FS jedoch fest in CCS codiert. Dies bedeutet, dass wir beim Starten neuer FS-Instanzen keine Möglichkeit haben, die Last zwischen ihnen zu verteilen. Im nächsten Teil werden wir den clientseitigen Lastausgleich mit Ribbon aktivieren.

Vollständiger Beispielcode

/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() { } } 

Source: https://habr.com/ru/post/de485094/


All Articles