Spring Boot 2 發佈與調用REST服務

来源:https://www.cnblogs.com/gdjlc/archive/2019/09/21/11565311.html
-Advertisement-
Play Games

一、發佈REST服務 二、使用RestTemplae調用服務 三、使用Feign調用服務 ...


開發環境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8

一、發佈REST服務

1、IDEA新建一個名稱為rest-server的Spring Boot項目

2、新建一個實體類User.cs

package com.example.restserver.domain;

public class User {
    String name;
    Integer age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}

2、新建一個控制器類 UserController.cs

package com.example.restserver.web;

import com.example.restserver.domain.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user(@PathVariable String name) {
        User u = new User();
        u.setName(name);
        u.setAge(30);
        return u;
    }
}

項目結構如下:

  

 訪問 http://localhost:8080/user/lc,頁面顯示:

{"name":"lc","age":30}

二、使用RestTemplae調用服務

1、IDEA新建一個名稱為rest-client的Spring Boot項目

2、新建一個含有main方法的普通類 RestTemplateMain.cs,調用服務

package com.example.restclient;

import com.example.restclient.domain.User;
import org.springframework.web.client.RestTemplate;

public class RestTemplateMain {
    public static void main(String[] args){
        RestTemplate tpl = new RestTemplate();
        User u = tpl.getForObject("http://localhost:8080/user/lc", User.class);
        System.out.println(u.getName() + "," + u.getAge());
    }
}

右鍵Run 'RestTemplateMain.main()',控制台輸出:lc,30

3、在bean裡面使用RestTemplate,可使用RestTemplateBuilder,新建類 UserService.cs

package com.example.restclient.service;

import com.example.restclient.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class UserService {
    @Autowired
    private RestTemplateBuilder builder;

    @Bean
    public RestTemplate restTemplate(){
        return builder.rootUri("http://localhost:8080").build();
    }

    public User userBuilder(String name){
        User u = restTemplate().getForObject("/user/" + name, User.class);
        return u;
    }

}

4、編寫一個單元測試類,來測試上面的UserService的bean。

package com.example.restclient.service;

import com.example.restclient.domain.User;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
public class UserServiceTest {
    @Autowired
    private UserService userService;

    @Test
    public void testUser(){
        User u = userService.userBuilder("lc");
        Assert.assertEquals("lc", u.getName());
    }
}

5、控制器類UserController.cs 中調用

配置在application.properties 配置埠和8080不一樣,如 server.port = 9001

    @Autowired
    private UserService userService;

    @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user(@PathVariable String name) {
        User u = userService.userBuilder(name);
        return u;
    }

三、使用Feign調用服務

繼續在rest-client項目基礎上修改代碼。

1、pom.xml添加依賴

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-core</artifactId>
            <version>9.5.0</version>
        </dependency>

        <dependency>
            <groupId>io.github.openfeign</groupId>
            <artifactId>feign-gson</artifactId>
            <version>9.5.0</version>
        </dependency>

2、新建介面 UserClient.cs

package com.example.restclient.service;

import com.example.restclient.domain.User;
import feign.Param;
import feign.RequestLine;


public interface UserClient {

    @RequestLine("GET /user/{name}")
    User getUser(@Param("name")String name);

}

3、在控制器類 UserController.cs 中調用

    @RequestMapping(value="/user2/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user2(@PathVariable String name) {
        UserClient service = Feign.builder().decoder(new GsonDecoder())
                                    .target(UserClient.class, "http://localhost:8080/");
        User u = service.getUser(name);
        return u;
    }

4、優化第3步代碼,並把請求地址放到配置文件中。

(1)application.properties 添加配置

application.client.url = http://localhost:8080

(2)新建配置類ClientConfig.cs

package com.example.restclient.config;

import com.example.restclient.service.UserClient;
import feign.Feign;
import feign.gson.GsonDecoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ClientConfig {
    @Value("${application.client.url}")
    private String clientUrl;

    @Bean
    UserClient userClient(){
        UserClient client = Feign.builder()
                .decoder(new GsonDecoder())
                .target(UserClient.class, clientUrl);
        return client;
    }
}

(3)控制器 UserController.cs  中調用

    @Autowired
    private  UserClient userClient;

    @RequestMapping(value="/user3/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user3(@PathVariable String name) {
        User u = userClient.getUser(name);
        return u;
    }

 

UserController.cs最終內容:

package com.example.restclient.web;

import com.example.restclient.domain.User;
import com.example.restclient.service.UserClient;
import com.example.restclient.service.UserService;
import feign.Feign;
import feign.gson.GsonDecoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private  UserClient userClient;

    @RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user(@PathVariable String name) {
        User u = userService.userBuilder(name);
        return u;
    }

    @RequestMapping(value="/user2/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user2(@PathVariable String name) {
        UserClient service = Feign.builder().decoder(new GsonDecoder())
                                    .target(UserClient.class, "http://localhost:8080/");
        User u = service.getUser(name);
        return u;
    }

    @RequestMapping(value="/user3/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
    public User user3(@PathVariable String name) {
        User u = userClient.getUser(name);
        return u;
    }
}

項目結構

 

先後訪問下麵地址,可見到輸出正常結果

http://localhost:9001/user/lc
http://localhost:9001/user2/lc2
http://localhost:9001/user3/lc3


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 場景 Ubuntu Server 上使用Docker Compose 部署Nexus(圖文教程): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/101111611 在上面已經實現部署Nexus後,初次登錄的預設賬戶密碼: adm ...
  • 場景 Docker-Compose簡介與Ubuntu Server 上安裝Compose: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100902301 Docker Compose基本使用-使用Compose啟動Tomcat ...
  • 場景 Docker-Compose簡介與Ubuntu Server 上安裝Compose: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/100902301 Docker Compose基本使用-使用Compose啟動Tomcat ...
  • 代理模式(Proxy): 代理模式就是給某一個對象提供一個代理,並由代理對象控制對原有對象的引用。在一些情況下,一個客戶不想或者不能直接引用一個對象,而代理對象可以在客戶端和目標對象之間起到中介的作用。例如windows桌面端的快捷方式就是一個代理。 代理模式按照使用目的可以分為: 1)遠程代理:為 ...
  • MapReduce計算流程 MapReduce計算流程 1 首先是通過程式員所編寫的MR程式通過命令行本地提交或者IDE遠程提交 2 一個MR程式就是一個Job,Job信息會給Resourcemanger,向Resourcemanger註冊信息 3 在註冊通過後,Job會拷貝相關的資源信息(從HDF ...
  • 理解JVM記憶體分配策略 三大原則+擔保機制 JVM分配記憶體機制有三大原則和擔保機制 具體如下所示: 優先分配到eden區 大對象,直接進入到老年代 長期存活的對象分配到老年代 空間分配擔保 對象優先在Eden上分配 如何驗證對象優先在Eden上分配呢,我們進行如下實驗。 列印記憶體分配信息 首先代碼如 ...
  • 場景 Effective Java 中文版Java核心技術 捲Ⅰ 基礎知識(第8版)Java語言程式設計-進階篇(原書第8版)瘋狂Java講義Java從入門到精通 第三版Java編程思想第4版重構-改善既有代碼的設計Head First Java 中文高清版Java從入門到精通Java核心技術 捲Ⅱ ...
  • 2019-09-21-23:00:26 今天看了很多博客網的博客,看完覺得自己的博客真的是垃圾中的垃圾 新手不知道怎樣寫博客,我也很想寫好一篇能讓人看的博客,但是目前水平不夠 只能慢慢改,今天的博客還是按照自己的方式寫吧,明天開始學習怎麼寫一篇好的博客 但是感覺有點難,加油,但是自己寫博客也是為了記 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...