iT邦幫忙

0

快速用Spring Boot 2 建立第一個API Service

Spring Boot在這微服務的時代開始,愈來愈普及API服務更加重要的使用工具,這篇文章最重要的一件事就是保證可以學會怎麼建立第一個API服務,從最基礎的服務設計開始,再逐步優化整個系統。

範例

檔案結構

Maven設定pom.xml

<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>
	<groupId>nandin-example</groupId>
	<artifactId>simple-api</artifactId>
	<version>1.0.0</version>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.4.3</version>
	</parent>
	<properties>
		<jarName>${project.artifactId}</jarName>
	</properties>
	<dependencies>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.8.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-consul-discovery</artifactId>
			<version>3.0.2</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
	</dependencies>
	<build>
		<finalName>app</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<finalName>${jarName}</finalName>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
				<version>2.22.0</version>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

服務設定application.yml

server:
  max-http-header-size: 10MB
  port : 8081
  connection-timeout: 60s
  servlet:
    context-path: /api
spring:
  application:
    name: api

Controller

package com.nandin.controller;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping(path = "/api/", produces = MediaType.APPLICATION_JSON_VALUE)
public class SampleAPIController {
	/**
	 * 用戶取消訂閱
	 * 
	 * @param payload
	 * @return
	 * @throws SQLException
	 * @throws Exception
	 */
	@RequestMapping(value = "greeting/{id}", method = RequestMethod.GET)
	public ResponseEntity<ResponseMessage> greeting(@PathVariable("id") String id)
			throws SQLException, Exception {
		return new ResponseEntity(HttpStatus.OK, "success");
	}
}

回應資料

package com.nandin.bean.api.response;
import java.io.Serializable;
/**
 * @author nandin.pao
 *
 */
public class ResponseMessage implements Serializable {
	/**
	 * 
	 */
	private static final long serialVersionUID = -5182086024346480861L;
	private int status = 0;
	private String message = "Success";
	public ResponseMessage(int status, String message) {
		super();
		this.status = status;
		this.message = message;
	}
	public int getStatus() {
		return status;
	}
	public void setStatus(int status) {
		this.status = status;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

主程式

啟動API Service

/**
 * 
 */
package com.agitg.api;
import org.springframework.boot.Banner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;
/**
 * @author nandin.pao
 *
 */
@Slf4j
@Configuration
@ServletComponentScan
@SpringBootApplication
public class MyApplication {
	/**
	 * 
	 */
	public MyApplication() {
		// TODO Auto-generated constructor stub
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SpringApplication application = new SpringApplication(MyApplication.class);
			application.setBannerMode(Banner.Mode.OFF);
			application.run(args);
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
			throw ex;
		}
	}
}

啟用服務

讓我們啟用MyApplicaton.java

17:48:33.996 [main] INFO  com.nandin.api.MyApplication - Starting MyApplication using Java 1.8.0_111 on Nandin.local with PID 14216 
17:48:33.997 [main] DEBUG com.nandin.api.MyApplication - Running with Spring Boot v2.4.3, Spring v5.3.4
17:48:33.998 [main] INFO  com.nandin.api.MyApplication - No active profile set, falling back to default profiles: default
17:48:38.723 [main] INFO  com.nandin.api.MyApplication - Started MyApplication in 25.299 seconds (JVM running for 25.983)

尚未有邦友留言

立即登入留言