最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringCloud中使用webclient(get和post)請求微服務接口數(shù)據(jù)

 更新時間:2024年10月19日 14:06:27   作者:全棧工程師進階  
在SpringCloud項目中使用WebClient調用微服務時,涉及配置WebClient、發(fā)起get和post請求等操作,如請求頭設置、服務地址配置、數(shù)據(jù)轉換處理、異常處理等,避免在循環(huán)中使用WebClient請求、路徑設置細節(jié)以及數(shù)據(jù)返回處理技巧,本文旨在幫助理解和應用WebClient進行微服務調用

在SpringCloud項目中使用WebClient調用微服務時,涉及配置WebClient、發(fā)起get和post請求等操作,如請求頭設置、服務地址配置、數(shù)據(jù)轉換處理、異常處理等,避免在循環(huán)中使用WebClient請求、路徑設置細節(jié)以及數(shù)據(jù)返回處理技巧,本文旨在幫助理解和應用WebClient進行微服務調用。

配置WebClient

首先我們在SpringCloud項目中配置WebClient,如下所示:

@Component
public class WebClientConfig {
    @Bean
    @LoadBalanced
    public WebClient.Builder webClientBuilder() {
        return WebClient.builder();
    }
}

然后在方法中引用:

@Resource
private WebClient.Builder webClientBuilder;

調用微服務接口

主要圍繞get和post請求來請求微服務接口數(shù)據(jù),如下:

1、Get請求

 public Mono<FileShare> getSharedFriends(String fileId, LoginUser loginUser) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            String userJson = mapper.writeValueAsString(loginUser);
            WebClient webClient = webClientBuilder.baseUrl("http://space-service").build();

            return webClient.get()
                    .uri(uriBuilder -> uriBuilder
                            // 注意:path中不能添加http://space-service,應該在上面添加
                            .path("/crud/file/getSharedFriends")
                            .queryParam("fileId", fileId)
                            .build())
                    // 將用戶信息傳遞給下游接口
                    .header(UserContext.USER, userJson)
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<ResultSuccess<Object>>() {})
                    .flatMap(resultSuccess -> {
                        log.info("resultSuccess={}", JSONArray.toJSONString(resultSuccess));
                        if (resultSuccess == null || resultSuccess.getData() == null) {
                            log.error("Received null data from server");
                            return Mono.empty();  // 避免 NullPointerException
                        }
                        log.info("resultSuccess.getData()={}", resultSuccess.getData());

                        ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper
                        FileShare fileShare = objectMapper.convertValue(resultSuccess.getData(), FileShare.class);

                        return Mono.just(fileShare);
                    })
                    .onErrorResume(e -> {
                        log.error("Error retrieving FileShare: {}", e.getMessage());
                        return Mono.empty();
                    });
        } catch (Exception ex) {
            log.info("getSharedFriends Exception ={}", ex.getMessage());
            return Mono.empty();
        }
    }

解釋一下上面的代碼:

  1. 我們在header中添加請求頭包含用戶信息數(shù)據(jù)傳遞給下游接口
  2. webClientBuilder.baseUrl中設置服務地址
  3. 使用bodyToMono轉換返回來的數(shù)據(jù),當然你可以寫自己的類型或者String.class
  4. flatMap處理轉換好的數(shù)據(jù)并返回
  5. 如果出現(xiàn)異常使用onErrorResume來處理
  6. queryParam添加?請求參數(shù)

然后我們可以處理接口返回來的數(shù)據(jù)

Mono<FileShare> fs = spaceWebClient.getSharedFriends(fileId, loginUser);
            return fs.switchIfEmpty(Mono.defer(() -> {
                        // 返回一個空的 FileShare 對象,以保持類型一致
                        FileShare emptyFileShare = new FileShare();  // 或者根據(jù)你的需求設置合適的默認值
                        return Mono.just(emptyFileShare);  // 返回類型為 Mono<FileShare>
                    })
            ).flatMap(fileShare -> {
                log.info("fileShare = {}", fileShare);
                List<String> uids = new ArrayList<>();
                List<User> user;
                uids.add(loginUser.getUid());
                if (fileShare == null || fileShare.getFriendIds() == null || fileShare.getFriendIds().isEmpty()) {
                    user = userService.getUserByName(uids, userName, 5);
                    return Mono.just(ResponseEntity.ok(new ResultSuccess<>(user)));
                } else {
                    uids.addAll(fileShare.getFriendIds());
                    user = userService.getUserByName(uids, userName, 5);
                }
                return Mono.just(ResponseEntity.ok(new ResultSuccess<>(user)));
            });

注意:如果webclient方法中返回Mono.empty(),則不會進入flatMap方法中,所以我們在switchIfEmpty方法中默認設置一個值

上面的flatMap處理你返回的接口數(shù)據(jù),這樣就完成了Get請求示例,下面看看Post請求。

2、Post請求

跟Get一樣,代碼如下:

public Mono<List<NotifyRemind>> queryNotifyBy(LoginUser loginUser, String senderId, String objId, List<String> recipientIds) {
        try {
            ObjectMapper mapper = new ObjectMapper();

            NotifyRemindRequest  notifyRemindRequest = new NotifyRemindRequest();
            notifyRemindRequest.setSenderId(senderId);
            notifyRemindRequest.setObjectId(objId);
            notifyRemindRequest.setRecipientIds(recipientIds);

            String userJson = mapper.writeValueAsString(loginUser);
            WebClient webClient = webClientBuilder.baseUrl("http://notify-service").build();

            return webClient.post()
                    .uri(uriBuilder -> uriBuilder
                            // 注意:path中不能添加http://space-service,應該在上面添加
                            .path("/crud/remind/queryBy")
                            .build())
                    .bodyValue(notifyRemindRequest)
                    // 將用戶信息傳遞給下游接口
                    .header(UserContext.USER, userJson)
                    .retrieve()
                    .bodyToMono(new ParameterizedTypeReference<ResultInfo<Object>>() {})
                    .flatMap(resultInfo -> {
                        log.info("resultSuccess={}", JSONArray.toJSONString(resultInfo));
                        if (resultInfo == null || resultInfo.getData() == null) {
                            List<NotifyRemind> empty = new ArrayList<>();
                            log.error("Received null data from server");
                            return Mono.just(empty);  // 避免 NullPointerException
                        }
                        ObjectMapper objectMapper = new ObjectMapper(); // Jackson ObjectMapper
                        // 使用 TypeReference 來指定目標類型
                        List<NotifyRemind> notifyReminds = objectMapper.convertValue(
                                //注意:不要使用List.class,因為返回的是List<LinkedHashMap>,改成:new TypeReference<>() {}
                                resultInfo.getData(), new TypeReference<>() {});
                        return Mono.just(notifyReminds);
                    })
                    .onErrorResume(e -> {
                        log.error("Error retrieving FileShare: {}", e.getMessage());
                        return Mono.empty();
                    });
        } catch (Exception ex) {
            log.info("getSharedFriends Exception ={}", ex.getMessage());
            return Mono.empty();
        }
    }

除了bodyValue添加請求參數(shù)類,其它的跟Get請求類似,不過有個注意點:

objectMapper.convertValue轉換成自己想要的List<NotifyRemind>類型時

請使用:

objectMapper.convertValue(resultInfo.getData(), new TypeReference<>() {})

不要使用:

objectMapper.convertValue(resultInfo.getData(), List.class)

接著我們在Controller層來接收下返回的接口數(shù)據(jù):

Mono<List<NotifyRemind>> listMono = notifyWebClient.queryNotifyBy(loginUser, loginUser.getUid(), fileId, fids);

listMono.subscribe(res -> {
    log.info("result:{}", res);
    if (res.isEmpty()) {
        for (String fid : fids) {
            sendNotify(loginUser, file, fid);
        }
    } else {
        // 找出 fids 中不存在于 notifyRemind.id 的值
        List<String> missingIds = fids.stream()
                .filter(fid -> res.stream().noneMatch(recipient -> recipient.getRecipientId().equals(fid)))
                .collect(Collectors.toList());
        for (String fid : missingIds) {
            sendNotify(loginUser, file, fid);
        }
    }
});

注意

1、Mono如果你沒使用的話則它不會請求接口,如:

Mono<FileShare> fs = spaceWebClient.getSharedFriends(fileId, loginUser);

這段代碼它不會請求接口,只有加上上面的.flatMap才會正常請求
2、不要把WebClient的請求放到循環(huán)中,如while和for
3、path是設置路徑,服務名需要在webClientBuilder.baseUrl中設置
4、因為我不想返回數(shù)據(jù),所以使用.subscribe方法來接收

總結

到此這篇關于SpringCloud中使用webclient(get和post)請求微服務接口數(shù)據(jù)的文章就介紹到這了,更多相關SpringCloud中用webclient調用微服務內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Mybatis中的@Select、foreach用法

    Mybatis中的@Select、foreach用法

    這篇文章主要介紹了Mybatis中的@Select、foreach用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-08-08
  • java實現(xiàn)從url路徑中下載pdf文檔到本地

    java實現(xiàn)從url路徑中下載pdf文檔到本地

    這篇文章主要為大家詳細介紹了java實現(xiàn)從url路徑中下載pdf文檔到本地,文中的示例代碼講解詳細,具有一定的借鑒價值,有需要的小伙伴可以了解下
    2025-11-11
  • 常用json與javabean互轉的方法實現(xiàn)

    常用json與javabean互轉的方法實現(xiàn)

    這篇文章主要介紹了常用json與javabean互轉的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • JAVA技術實現(xiàn)上傳下載文件到FTP服務器(完整)

    JAVA技術實現(xiàn)上傳下載文件到FTP服務器(完整)

    這篇文章主要介紹了JAVA技術實現(xiàn)上傳下載文件到FTP服務器(完整),本文使用 Apache Jakarta Commons Net(commons-net-3.3.jar) 基于FileZilla Server服務器實現(xiàn)FTP服務器上文件的上傳/下載/刪除等操作,需要的朋友可以參考下
    2015-07-07
  • Java倒計時三種實現(xiàn)方式代碼實例

    Java倒計時三種實現(xiàn)方式代碼實例

    這篇文章主要介紹了Java倒計時三種實現(xiàn)方式代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-07-07
  • 解決Mybatis在IDEA中找不到mapper映射文件的問題

    解決Mybatis在IDEA中找不到mapper映射文件的問題

    這篇文章主要介紹了解決Mybatis在IDEA中找不到mapper映射文件的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-10-10
  • Java數(shù)據(jù)結構及算法實例:漢諾塔問題 Hanoi

    Java數(shù)據(jù)結構及算法實例:漢諾塔問題 Hanoi

    這篇文章主要介紹了Java數(shù)據(jù)結構及算法實例:漢諾塔問題 Hanoi,本文直接給出實現(xiàn)代碼,代碼中包含大量注釋,需要的朋友可以參考下
    2015-06-06
  • Java中Spring技巧之擴展點的應用

    Java中Spring技巧之擴展點的應用

    這篇文章主要介紹了Java中Spring技巧之擴展點的應用,下文Spring容器的啟動流程圖展開其內容的相關資料,具有一定的參考價值,需要的小伙伴可以參考一下
    2022-04-04
  • Druid(新版starter)在SpringBoot下的使用教程

    Druid(新版starter)在SpringBoot下的使用教程

    Druid是Java語言中最好的數(shù)據(jù)庫連接池,Druid能夠提供強大的監(jiān)控和擴展功能,DruidDataSource支持的數(shù)據(jù)庫,這篇文章主要介紹了Druid(新版starter)在SpringBoot下的使用,需要的朋友可以參考下
    2023-05-05
  • 使用idea自動生成序列化ID全過程

    使用idea自動生成序列化ID全過程

    這篇文章主要介紹了使用idea自動生成序列化ID全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09

最新評論

巴彦淖尔市| 防城港市| 盱眙县| 辽宁省| 宁河县| 浠水县| 丰原市| 枣阳市| 泾阳县| 松桃| 汝州市| 安泽县| 福清市| 长泰县| 资中县| 思茅市| 高陵县| 江华| 亚东县| 普兰县| 巴青县| 桃源县| 新建县| 牡丹江市| 吉水县| 瑞金市| 肥乡县| 梁河县| 宿迁市| 南木林县| 治多县| 班玛县| 十堰市| 玛纳斯县| 兴隆县| 崇阳县| 吉木萨尔县| 贡山| 来安县| 万盛区| 湟中县|