Spring Boot 微服務小案例

創建一個Maven(maven-archetype-quickstart)項目,在pom.xml文件配置Spring Boot 依賴

配置與<properties 同級的文件
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.2.RELEASE</version>
  </parent>
配置與<dependency 平級的文件
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
配置與<dependencies 同級的文件
<build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
 </build>

配置完成之後保存文件,會自動下載相關jar包
然後在項目文件夾下創建class類,寫入功能代碼(這裏是做openlayer模擬報警的一個功能測試,該類返回一個json數據格式的經緯度,根據需求放入相關的功能代碼)

package simple.test.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
//@RestController 標註是一個Controller類 並且支持json數據格式輸出
@RestController
public class waner {
	@RequestMapping("/warninfo")
	public String warenInfo() {
		double x = Math.random() * 2 + 115;
		double y = Math.random() * 2 + 39;
		String str = "{\"lon\":" + x + ",\"lat\":" + y +"}";
		return str;
	}
}
這裏需要創建一個CorsConfig.java文件,解決跨域問題
package simple.test;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CorsConfig implements WebMvcConfigurer {
	
	@Override
	public void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
		.allowedOrigins("*")
		.allowCredentials(true)
		.allowedMethods("GET","POST","DELETE","PUT","PATCH")
		.maxAge(3600);
	}
}
創建resources文件夾裏面放置一個文件,文件名爲application.properties,最好不要改動該文件名,在文件配置一個端口
server.port = 8012
下面在主類文件中寫入相關代碼
package simple.test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

//@SpringBootApplication 代表springboot的啓動類 用來標註主程序類 說明是一個springboot應用
@SpringBootApplication
public class App extends SpringBootServletInitializer
{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
		//將springboot應用驅動起來
        SpringApplication.run(App.class, args);
    }
}
新建包結構

Spring Boot 微服務

啓動Spring Boot 微服務

運行結果

頁面訪問結果

Spring Boot 微服務結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章