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

2023-10-26 14:11:16 浏览数 (1)

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

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

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

项目结构
pom.xml
代码语言:javascript复制
<?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

代码语言:javascript复制
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

代码语言:javascript复制
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

代码语言:javascript复制
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;
	}
}

应用程序属性

代码语言:javascript复制
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

代码语言:javascript复制
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 上运行

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

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

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

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

代码语言:javascript复制
http://localhost:8000/currency-exchange-sample/fromCurrency/USD/toCurrency/INR

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

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

代码语言:javascript复制
http://localhost:8000/currency-exchange-sample/fromCurrency/EUR/toCurrency/INR
代码语言:javascript复制
http://localhost:8000/currency-exchange-sample/fromCurrency/AUD/toCurrency/INR

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

0 人点赞