首页 > 编程语言 >如何使用Java Spring Boot 创建一个微服务项目 一?

如何使用Java Spring Boot 创建一个微服务项目 一?

时间:2023-10-24 10:32:33浏览次数:35  
标签:Java spring toCurrency boot Boot springframework fromCurrency Spring org

如何使用Java Spring Boot 创建一个微服务项目一?

微服务现在更流行。它们可以用任何语言编写。在这篇文章中,让我们看看Spring Boot微服务。在本文中,我们看到一个基础项目currency-exchange-sample-service,它具有业务逻辑,并且可以在另一个项目 currency-conversion-sample-service 中调用

微服务1:货币兑换样本服务

项目结构

如何使用Java Spring Boot 创建一个微服务项目 一?_ci

 

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 
							https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.gfg.microservices</groupId>
	<artifactId>currency-exchange-sample-service</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>currency-exchange-sample-service</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.RC2</spring-cloud.version>
	</properties>

	<dependencies>
	
		<!-- Starter for building web, including RESTful, 
			applications using Spring MVC. -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>
		<!-- The spring-boot-devtools module can be included in any 
			project to provide additional development-time features -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</dependency>
		<!-- H2 is an open-source lightweight Java database -->
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>			 
			<scope>runtime</scope> 
		</dependency> 
		<!-- starter for using Spring Data JPA with Hibernate. -->
		<dependency> 
		<groupId>org.springframework.boot</groupId> 
		<artifactId>spring-boot-starter-data-jpa</artifactId> 
		<version>2.1.3.RELEASE</version> 
		</dependency> 
		<!-- provides secured endpoints for monitoring 
			and managing your Spring Boot application -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</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-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>

</project>


让我们看看重要的文件 

CurrencyExchangeServiceSampleApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
// 这与使用 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 以及它们的默认属性等效:
public class CurrencyExchangeServiceSampleApplication {

	public static void main(String[] args)
	{
		SpringApplication.run(
			CurrencyExchangeServiceSampleApplication.class,
			args);
	}
}


CurrencyExchangeSampleController.java

import java.math.BigDecimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class CurrencyExchangeSampleController {
	@Autowired private Environment environment;

	@GetMapping(
		"/currency-exchange-sample/fromCurrency/{fromCurrency}/toCurrency/{toCurrency}")
	public ExchangeValue
	retrieveExchangeValue(@PathVariable String fromCurrency,
						@PathVariable String toCurrency)
	{
		// Here we need to write all of our business logic
		BigDecimal conversionMultiple = null;
		ExchangeValue exchangeValue = new ExchangeValue();
		if (fromCurrency != null && toCurrency != null) {
			if (fromCurrency.equalsIgnoreCase("USD")
				&& toCurrency.equalsIgnoreCase("INR")) {
				conversionMultiple = BigDecimal.valueOf(78);
			}
			if (fromCurrency.equalsIgnoreCase("INR")
				&& toCurrency.equalsIgnoreCase("USD")) {
				conversionMultiple
					= BigDecimal.valueOf(0.013);
			}
			if (fromCurrency.equalsIgnoreCase("EUR")
				&& toCurrency.equalsIgnoreCase("INR")) {
				conversionMultiple = BigDecimal.valueOf(82);
			}
			if (fromCurrency.equalsIgnoreCase("AUD")
				&& toCurrency.equalsIgnoreCase("INR")) {
				conversionMultiple = BigDecimal.valueOf(54);
			}
		}
		// setting the port
		exchangeValue = new ExchangeValue(
			1000L, fromCurrency, toCurrency,
			conversionMultiple);
		exchangeValue.setPort(Integer.parseInt(
			environment.getProperty("local.server.port")));
		return exchangeValue;
	}
}

ExchangeValue.java

import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

// @Entity annotation defines that a class can be mapped to
// a table
@Entity

// Representation of the table name
@Table(name = "Exchange_Value")
public class ExchangeValue {
	// The @Id annotation is inherited from
	// javax.persistence.Id, indicating the member field
	// below is the primary key of the current entity
	@Id @Column(name = "id") private Long id;
	@Column(name = "currency_from")
	private String fromCurrency;
	@Column(name = "currency_to") private String toCurrency;
	@Column(name = "conversion_multiple")
	private BigDecimal conversionMultiple;
	@Column(name = "port") private int port;

	public ExchangeValue() {}

	// generating constructor using fields
	public ExchangeValue(Long id, String fromCurrency,
						String toCurrency,
						BigDecimal conversionMultiple)
	{
		super();
		this.id = id;
		this.fromCurrency = fromCurrency;
		this.toCurrency = toCurrency;
		this.conversionMultiple = conversionMultiple;
	}

	// generating getters
	public int getPort() { return port; }

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

	public Long getId() { return id; }

	public String getFrom() { return fromCurrency; }

	public String getTo() { return toCurrency; }

	public BigDecimal getConversionMultiple()
	{
		return conversionMultiple;
	}
}

应用程序属性

spring.application.name=货币交换样本服务
server.port=8000 #端口号的表示。我们也可以在运行配置中设置不同的端口号
spring.jpa.show-sql=true #显示SQL
spring.h2.console.enabled=true  
spring.datasource.platform=h2 #由于我们使用的是h2数据源
spring.datasource.url=jdbc:h2:mem:gfg

## data.sql

insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)  
values(10001,'USD', 'INR' ,65,0);  
insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)  
values(10002,'EUR', 'INR' ,82,0);  
insert into exchange_value(id,currency_from,currency_to,conversion_multiple,port)  
values(10003,'AUD', 'INR' ,53,0);

默认情况下,它已设置为在端口 8000 上运行。我们可以创建另一个实例,并可以通过以下方式使项目在端口 8001 上运行

如何使用Java Spring Boot 创建一个微服务项目 一?_spring_02

由于这是Spring Boot应用程序,因此它可以作为Java应用程序正常运行

如何使用Java Spring Boot 创建一个微服务项目 一?_ci_03

如果我们设置在两个不同的端口上运行应用程序,我们将得到以下选项

如何使用Java Spring Boot 创建一个微服务项目 一?_spring_04

让我们选择第一个。运行应用程序时,在控制台中,我们看到

如何使用Java Spring Boot 创建一个微服务项目 一?_spring_05

从控制台中,我们可以看到它使用默认的Tomcat,并且项目运行在端口8080上。由于我们使用了3个插入脚本,因此会自动创建表并插入数据。我们可以做到以下几点 

http://localhost:8000/currency-exchange-sample/fromCurrency/USD/toCurrency/INR

如何使用Java Spring Boot 创建一个微服务项目 一?_java_06

当这个URL被点击时,它将被重定向到控制器,fromCurrency被视为“USD”,toCurrency被视为“INR”

同样,我们可以执行以下 URL

http://localhost:8000/currency-exchange-sample/fromCurrency/EUR/toCurrency/INR

如何使用Java Spring Boot 创建一个微服务项目 一?_ci_07

http://localhost:8000/currency-exchange-sample/fromCurrency/AUD/toCurrency/INR

如何使用Java Spring Boot 创建一个微服务项目 一?_spring_08

因此,根据我们的业务需求,我们可以将业务逻辑添加到控制器文件中

标签:Java,spring,toCurrency,boot,Boot,springframework,fromCurrency,Spring,org
From: https://blog.51cto.com/demo007x/8001219

相关文章

  • 如何使用Java Spring Boot 创建一个微服务项目 二?
    如何使用JavaSpringBoot创建一个微服务项目二?上一篇我们已经链接了如何使用JavaSpringBoot创建一个微服务项目一?这一篇我们接着实现第二部分微服务2:货币兑换样本服务这也是一个maven项目pom.xml<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apac......
  • JavaScript 将对象转换为数组
    JavaScript将对象转换为数组在JavaScript中,你可以使用不同的方法将对象转换为数组,具体取决于对象的结构和你希望在数组中得到什么样的数据。以下是一些常见的方法:Object.keys()方法:这种方法将对象的键转换为数组。constobj={a:1,b:2,c:3};constarr=Object......
  • Java使用多线程异步执行批量更新操作方法
    一、核心技术Java提供了Executor框架来实现多线程任务的执行。我们可以通过创建ExecutorService对象来管理线程池,然后将任务提交给这个线程池执行。Executor框架的优点在于,它可以自动管理线程数量,以最大化利用CPU和内存资源。二、具体实现方法1、创建一个数据更新任务类,实现Run......
  • java.security.provider.getservice blocked
    bug:https://bugs.openjdk.org/browse/JDK-8206333堆栈:"Osp-Common-Business-Thread-572"Id=1723BLOCKEDatjava.security.Provider.getService(Provider.java:1035)atsun.security.jca.ProviderList.getService(ProviderList.java:332)atsun.security.jca......
  • 入门篇-其之六-Java运算符(中)
    祝所有程序员,1024节日快乐!!!......
  • 8、SpringMVC之RESTful案例
    阅读本文前,需要先阅读SpringMVC之RESTful概述8.1、前期工作8.1.1、创建实体类Employeepackageorg.rain.pojo;importjava.io.Serializable;/***@authorliaojy*@date2023/10/19-21:31*/publicclassEmployeeimplementsSerializable{privateInte......
  • 一天吃透Java并发面试八股文
    内容摘自我的学习网站:topjavaer.cn分享50道Java并发高频面试题。线程池线程池:一个管理线程的池子。为什么平时都是使用线程池创建线程,直接new一个线程不好吗?嗯,手动创建线程有两个缺点不受控风险频繁创建开销大为什么不受控?系统资源有限,每个人针对不同业务都可以手动......
  • 华为云服务器+java环境配置
     在华为云耀云服务器L实例(官网地址https://www.huaweicloud.com/product/hecs-light.html)中,我们有着部署管理系统的场景,本期教程中,我们需要开始部署管理系统,在前面教程中我们已经配置好了服务器的数据库以及基本的运行环境,现在我们需要开始部署java环境的配置,来为后期的项目......
  • How to fix EventSource onmessage not working in JavaScript All in One
    HowtofixEventSourceonmessagenotworkinginJavaScriptAllinOneSSE:Server-SentEvents/服务端推送error❌window.addEventListener(`load`,(e)=>{console.log(`pageloaded✅`);if(!!window.EventSource){constimg=document.querySelecto......
  • uboot配置usbhost及代码初步分析--Apple的学习笔记
    一,前言之前uboot没配置过usb,但是现在uboot基于DM模型基本和linuxdriver类似了。那么为了学习linuxdriver,我可以先学习uboot来做技术储备也是一样的。而且usb在uboot上应该也有用武之地,所以有必要进行刻意练习。二,分析1,之前对发现driver用了wraper的方式来打包进行绑定,我理解唯一......