欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot調(diào)用外部接口的幾種方式

 更新時(shí)間:2024年10月25日 10:51:58   作者:one_smail  
SpringBoot應(yīng)用中,調(diào)用外部接口是微服務(wù)架構(gòu)常見需求,本文主要介紹了SpringBoot調(diào)用外部接口的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

使用FeignClient調(diào)用

FeignClient調(diào)用大多用于微服務(wù)開發(fā)中,各服務(wù)之間的接口調(diào)用。它以Java接口注解的方式調(diào)用HTTP請(qǐng)求,使服務(wù)間的調(diào)用變得簡(jiǎn)單

1、在使用方引入依賴

<!-- Feign注解 這里openFeign的版本要和自己使用的SpringBoot匹配-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
    <!-- <version>4.0.1</version> -->
</dependency>

2、服務(wù)接口調(diào)用方

2.1、在啟動(dòng)類上加上@EnableFeigncliens注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class StudyfeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(StudyfeignApplication.class, args);
        System.out.println("項(xiàng)目啟動(dòng)成功");
    }

}

2.2、編寫Feign接口調(diào)用服務(wù)controller層

import com.hysoft.studyfeign.service.SysUserClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("feign")
public class SysUserController {

    @Autowired
    private SysUserClient sysUserClient;

    @PostMapping("getUserId")
    public void getUserId(String userId){
        this.sysUserClient.getUserById(userId);
    }

}

2.3、服務(wù)接口調(diào)用service層

feign的客戶端需要使用@FeignClient注解進(jìn)行表示,這樣掃描時(shí)才知道這是一個(gè)feign客戶端。@FeignClient最常用的就兩個(gè)屬性,一個(gè)name,用于給客戶端定義一個(gè)唯一的名稱,另一個(gè)就是url,用于定義該客戶端調(diào)用的遠(yuǎn)程地址。url中的內(nèi)容,可以寫在配置文件application.yml中,便于管理

@Service
@FeignClient(name = "feign-service",url = "${master-getuserbyId}")
public interface SysUserClient {

    @PostMapping("/master/test")
    String getUserById(String id);

}

application.yml中的配置如下

server:
  port: 8081
master-getuserbyId: http://localhost:8080

3、服務(wù)接口提供者

對(duì)于接口提供者來說沒有特別要求,和正常的接口開發(fā)一樣

4、說明

需要說明的是,在接口調(diào)用方,可以繼續(xù)拓展service層,書寫service實(shí)現(xiàn)層,進(jìn)一步進(jìn)行拓展    

import org.springframework.stereotype.Service;

@Service
public class SysUserClientImpl implements SysUserClient{
    @Override
    public String getUserById(String id) {
        return "";
    }
}

使用RestTemplate調(diào)用

RestTemplate中幾個(gè)常用的方法:getForObject()、getForEntity()、postForObject()、postForEntity()。其中,getForObject() 和 getForEntity() 方法可以用來發(fā)送 GET 請(qǐng)求

1、引入依賴

  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
  </dependency>

2、RestTemplateConfig配置類

SimpleClientHttpRequestFactory類對(duì)應(yīng)的HTTP庫是JDK自帶的HttpUrlConnection,當(dāng)然我們可以根據(jù)自身的需求使用其他的HTTP庫,例如HttpComponentsAsyncClientHttpRequestFactory

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setReadTimeout(5000);//單位為ms
        factory.setConnectTimeout(5000);//單位為ms
        return factory;
    }
}

3、接口調(diào)用

@RestController
public class TestRestTemplate {
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/saveUser")
    public void saveUser(String userId) {
        String url = "http://127.0.0.1:8080/master/test";
        Map map = new HashMap<>();
        map.put("userId", "hy001");
        String results = restTemplate.postForObject(url, map, String.class);
    }
  }

使用WebClient調(diào)用

Spring3.0引入了RestTemplate,但是在后來的官方源碼中介紹,RestTemplate有可能在未來的版本中被棄用,所謂替代RestTemplate,在Spring5中引入了WebClient作為異步的非阻塞、響應(yīng)式的HTTP客戶端。

1、引入依賴

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>

2、接口調(diào)用示例

public class TestWebClient {
    @Test
    public void doGet() {
        String userId = "郭郭";
        String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId={userId}";
        Mono<String> mono = WebClient
                //創(chuàng)建WebClient實(shí)例
                .create()
                //方法調(diào)用,WebClient中提供了多種方法
                .get()
                //請(qǐng)求url
                .uri(url, userId)
                //獲取響應(yīng)結(jié)果
                .retrieve()
                //將結(jié)果轉(zhuǎn)換為指定類型
                .bodyToMono(String.class);
        //返回最終結(jié)果:block是阻塞的/subscribe()非阻塞式獲取響應(yīng)結(jié)果
        System.out.println("響應(yīng)結(jié)果:" + mono.block());
    }
    @Test
    public void doPost() {
        Map map = new HashMap<>();
        map.put("name", "郭郭");
        String requestBody = JSON.toJSONString(map);
        String url = "http://127.0.0.1:8080/master/test/saveUser";
        Mono<String> mono = WebClient
                //創(chuàng)建WebClient實(shí)例
                .create()
                //方法調(diào)用,WebClient中提供了多種方法
                .post()
                //請(qǐng)求url
                .uri(url)
                //指定請(qǐng)求的Content-Type為JSON
                .contentType(MediaType.APPLICATION_JSON)
                //使用bodyValue方法傳遞請(qǐng)求體
                .bodyValue(requestBody)
                //獲取響應(yīng)結(jié)果
                .retrieve()
                //將結(jié)果轉(zhuǎn)換為指定類型
                .bodyToMono(String.class);
        //返回最終結(jié)果:block是阻塞的/subscribe()非阻塞式獲取響應(yīng)結(jié)果
        System.out.println("響應(yīng)結(jié)果:" + mono.block());
    }
}

在上述doPost請(qǐng)求中,我們的請(qǐng)求接口入?yún)⑹且粋€(gè)Map,但是需要轉(zhuǎn)換為JSON格式傳遞,這是因?yàn)閃ebClient默認(rèn)是使用JSON序列化的。

使用Apache HttpClient調(diào)用

public class TestHttpClient {
    @Test
    public void doGet() throws IOException {
        //步驟一:創(chuàng)建httpClient實(shí)例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //步驟二:創(chuàng)建HTTP請(qǐng)求
        HttpGet httpGet = new HttpGet("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=郭郭");
        //步驟三:發(fā)送請(qǐng)求并獲取響應(yīng)數(shù)據(jù)
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //步驟四:處理響應(yīng)數(shù)據(jù)
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        //步驟五:關(guān)閉httpClient和response
        response.close();
        httpClient.close();
    }
    @Test
    public void doPost() throws IOException {
        //步驟一:創(chuàng)建httpClient實(shí)例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //步驟二:創(chuàng)建HTTP請(qǐng)求
        HttpPost httpPost = new HttpPost("http://127.0.0.1:8094/masterdata/sysUser/saveUser");
        //步驟三:設(shè)置請(qǐng)求體數(shù)據(jù),使用JSON格式
        Map map = new HashMap<>();
        map.put("name", "郭郭");
        String requestBody = JSON.toJSONString(map);
        StringEntity stringEntity = new StringEntity(requestBody, "UTF-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);
        
        //步驟四:發(fā)送請(qǐng)求并獲取響應(yīng)數(shù)據(jù)
        CloseableHttpResponse response = httpClient.execute(httpPost);
        //步驟五:處理響應(yīng)數(shù)據(jù)
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        //步驟五:關(guān)閉httpClient和response
        response.close();
        httpClient.close();
    }
}

使用HttpURLConnection調(diào)用

public class TestHttpURLConnection {

    @Test
    public void doGet() throws IOException {
        String userId = "郭郭";  // 參數(shù)值
        userId = URLEncoder.encode(userId, "UTF-8"); // 對(duì)參數(shù)值進(jìn)行URL編碼
        //步驟一:創(chuàng)建URL對(duì)象
        URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/getSysUserById?userId=" + userId);
        //步驟二:打開連接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //步驟三:設(shè)置請(qǐng)求方式
        conn.setRequestMethod("GET");
        //步驟四:讀取響應(yīng)內(nèi)容
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        System.out.println(sb.toString());
    } 
    @Test
    public void doPost() throws IOException {
        //創(chuàng)建URL對(duì)象
        URL url = new URL("http://127.0.0.1:8094/masterdata/sysUser/saveUser");
        //打開連接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //設(shè)置請(qǐng)求方式
        conn.setRequestMethod("POST");
        // 設(shè)置請(qǐng)求頭
        conn.setRequestProperty("Content-Type", "application/json");
        //啟用輸出流
        conn.setDoOutput(true);
        //設(shè)置請(qǐng)求體數(shù)據(jù)
        Map map = new HashMap<>();
        map.put("name", "郭郭");
        String requestBody = JSON.toJSONString(map);
        //發(fā)送請(qǐng)求體數(shù)據(jù)
        try (DataOutputStream outputStream = new DataOutputStream(conn.getOutputStream())) {
            outputStream.write(requestBody.getBytes(StandardCharsets.UTF_8));
        }

        //讀取響應(yīng)內(nèi)容
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        reader.close();
        System.out.println(sb.toString());
    } 
  }

使用OkHttp調(diào)用

1、引入依賴

<!--okhttp依賴-->
  <dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.0.0</version>
  </dependency>

2、示例代碼

public class TestOkHttp {

    @Test
    public void doGet() throws IOException {
        OkHttpClient client = new OkHttpClient();
        String url = "http://127.0.0.1:8080/master/test/getSysUserById?userId=郭郭";
        Request request = new Request.Builder().url(url).build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            System.out.println(body.string());
        }
    }

    @Test
    public void doPost() throws IOException{
        OkHttpClient client = new OkHttpClient();
        String url = "http://127.0.0.1:8080/master/test/saveUser";
        MediaType mediaType = MediaType.get("application/json; charset=utf-8");
        //requestBody請(qǐng)求入?yún)?
        Map map = new HashMap<>();
        map.put("name", "admin");
        RequestBody requestBody = RequestBody.create(mediaType, JSON.toJSONString(map));
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try (Response response = client.newCall(request).execute()) {
            ResponseBody body = response.body();
            System.out.println(body.string());
        }
    }
}

使用AsyncHttpClient調(diào)用

1、引入依賴

<dependency>
      <groupId>org.asynchttpclient</groupId>
      <artifactId>async-http-client</artifactId>
      <version>2.12.3</version>
</dependency>

2、示例代碼

public class TestAsyncHttpClient {
    @Test
    public void doGet() throws IOException {
        try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {
            BoundRequestBuilder requestBuilder = client.prepareGet("http://127.0.0.1:8080/master/test/getSysUserById?userId=hy001");
            CompletableFuture<String> future = requestBuilder.execute()
                    .toCompletableFuture()
                    .thenApply(Response::getResponseBody);
            //使用join等待響應(yīng)完成
            String responseBody = future.join();
            System.out.println(responseBody);
        }
    }
    @Test
    public void doPost() throws IOException {
        try (AsyncHttpClient client = new DefaultAsyncHttpClient();) {
            BoundRequestBuilder requestBuilder = client.preparePost("http://127.0.0.1:8094/8080/master/test/saveUser");
            //requestBody請(qǐng)求入?yún)?
            Map map = new HashMap<>();
            map.put("name", "admin");
            String requestBody = JSON.toJSONString(map);
            requestBuilder.addHeader("Content-Type", "application/json");
            requestBuilder.setBody(requestBody);
            CompletableFuture<String> future = requestBuilder.execute()
                    .toCompletableFuture()
                    .thenApply(Response::getResponseBody);
            //使用join等待響應(yīng)完成
            String responseBody = future.join();
            System.out.println(responseBody);
        }
    }
  }

到此這篇關(guān)于SpringBoot調(diào)用外部接口的幾種方式的文章就介紹到這了,更多相關(guān)SpringBoot調(diào)用外部接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

最新評(píng)論