📜  从货币转换服务调用货币兑换服务

📅  最后修改于: 2021-01-11 02:26:01             🧑  作者: Mango

从货币兑换服务中调用货币兑换服务

我们已经准备好了货币兑换服务,并且已经设置了货币计算服务(currency-conversion-service)。现在,我们将从货币计算服务中调用货币兑换服务。

我们使用RestTemplate()构造函数来调用外部服务。让我们创建一个RestTemplate并尝试调用currency-exchange-service。

步骤1:选择货币转换服务项目。

步骤2:打开CurrencyConversionController.java并创建一个新的RestTemplate来调用currency-exchange-service应用程序。

步骤3:调用RestTemplate类的getForEntity()方法。

getForEntity():这是RestTemplate类的方法,该方法检索通过使用用于指定URL的HTTPGET方法的实体。它将响应转换并存储在ResponseEntity中。它返回ResponseEntity

参数:它接受两个参数:

  • URL: URL。
  • responseType:返回值的类型。
ResponseEntityresponseEntity=new RestTemplate().getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}", CurrencyConversionBean.class, uriVariables);

步骤4:在URL参数中,输入currency-converter-service的URL为http:// localhost:8000 / currency-exchange / from / {from} / to / {to} 。它从请求中获取变量{from}{to}的值。无论请求中有什么内容,我们都会将其发送到Currency-exchange-service。

步骤5:在上述网址中,我们需要传递两个值“ from”“ to”。为了传递值,请为URI变量创建一个Map。在URI中传递uriVariables作为参数。

MapuriVariables=new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);

步骤6:我们期望返回的响应类型是CurrencyConversionBean,因此将响应存储在CurrencyConversionBean中。

CurrencyConversionBean response=responseEntity.getBody();

CurrencyConversionController.java

package com.javatpoint.microservices.currencyconversionservice;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
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
{
@GetMapping("/currency-converter/from/{from}/to/{to}/quantity/{quantity}") //where {from} and {to} represents the column 
//returns a bean back
public CurrencyConversionBeanconvertCurrency(@PathVariable String from, @PathVariable String to, @PathVariableBigDecimal quantity)
{
//setting variables to currency exchange service
MapuriVariables=new HashMap<>();
uriVariables.put("from", from);
uriVariables.put("to", to);
//calling the currency-exchange-service
ResponseEntityresponseEntity=new RestTemplate().getForEntity("http://localhost:8000/currency-exchange/from/{from}/to/{to}", CurrencyConversionBean.class, uriVariables);
CurrencyConversionBean response=responseEntity.getBody();
//creating a new response bean and getting the response back and taking it into Bean
return new CurrencyConversionBean(response.getId(), from,to,response.getConversionMultiple(), quantity,quantity.multiply(response.getConversionMultiple()),response.getPort());
}
}

步骤7:独立运行两个服务。当我们运行货币换算时,它返回如下所示的响应:

转换倍数乘以数量,并返回totalCalculatedAmount 65000.00。这意味着$ 1000等于65000.00 INR。它还显示端口8000 ,该端口表示端口8000上正在运行其他服务(currency-exchange-service)。