SpringCloud微服務之跨服務調用后端接口


SpringCloud微服務系列博客:

SpringCloud微服務之快速搭建EurekaServer:https://blog.csdn.net/egg1996911/article/details/78787540
SpringCloud微服務之注冊服務至EurekaServer:https://blog.csdn.net/egg1996911/article/details/78859200
SpringCloud微服務之集成thymeleaf訪問html頁面/靜態頁面&熱部署:https://blog.csdn.net/egg1996911/article/details/78885045
SpringCloud微服務之部署SpringBoot項目至Linux服務器(CentOS):https://blog.csdn.net/egg1996911/article/details/78975945
SpringCloud微服務之使用SpringBoot搭建后端服務&配置MyBatis框架:https://blog.csdn.net/egg1996911/article/details/80215554


本文介紹如何跨服務調用后端接口,包含三種方式:

  1. 從前端使用AJAX調用后端接口
  2. 在后端使用HttpURLConnection訪問接口
  3. 在后端配合Eureka發現服務,使用RestTemplate調用接口

說明:

  • 從前端使用AJAX調用后端接口時,容易出現JS跨域問題,SpringBoot中解決跨域訪問的方法見博客:https://blog.csdn.net/egg1996911/article/details/79901620
  • 方式1和方式2需要知道被訪問的服務的ip地址
  • 方式3需要保證調用服務的一方和被調用服務的一方都注冊在同一個Eureka Server上

因此,如果是微服務體系架構,那么使用方式3是最好的選擇。方式3可以不用自己去管理服務ip信息,這樣在被調用服務的部署地址發生變化時,不需要修改自己的配置,而方式1和方式2都需要重新配置被調用服務的ip信息

以下均以從microapp調用microimage的服務接口為例:

1、使用AJAX調用后端接口

function loadImages() {
    $.ajax({
        url: "localhost:8089/images/getAll",
        type: "GET",
        data: {},
        async: false,
        timeout: 5000,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {
                var li = $('<li></li>');
                li.addClass("box");
                var a = $('<a></a>');
                a.attr("href", data[i].url);
                a.addClass("magnifier");
                var img = $('<img/>');
                img.attr("alt", data[i].description);
                img.attr("src", data[i].url);
                img.attr("height", "270px");
                img.attr("width", "370px");
                img.appendTo(li);
                img.appendTo(a);
                a.appendTo(li);
                li.appendTo($("#images"));
            }
        },
        error: function (xhr, textStatus) {
        }
    })
}
   
   
  
  
          

其中url參數處要填寫出被調用服務的ip:port/接口名,調用成功后接口返回值即為success函數中的data

2、使用HttpUrlConnection訪問接口

可以參考我的另一篇博文:https://blog.csdn.net/egg1996911/article/details/73822803

3、使用Eureka發現服務並調用接口

在啟動類中配置RestTemplate:

package com.deng.site;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@EnableDiscoveryClient
@SpringBootApplication
public class MicroAppApplication {
    public static void main(String[] args) {
        SpringApplication.run(MicroAppApplication.class, args);
    }

    @LoadBalanced
    @Bean
    RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

   
   
  
  
          

調用MICROIMAGE微服務接口:

package com.deng.site.service.impl;

import com.deng.site.service.ImageService;
import com.deng.site.vo.ImageVO;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
@PropertySource(value = {"classpath:application.properties"}, encoding = "utf-8")
public class ImageServiceImpl implements ImageService {
    @Autowired
    private RestTemplate restTemplate;

    @Value("${gateway.url}")
    private String gateway;

    @Override
    public List<ImageVO> getAllImages() {
        List<ImageVO> imageVOs = new ArrayList<>();

        String url = "http://MICROIMAGE/images/getAll";
        String result = restTemplate.getForObject(url, String.class);
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            JsonNode jsonRes = objectMapper.readTree(result);
            for (int i = 0; i < jsonRes.size(); i++) {
                JsonNode jsonNode = jsonRes.get(i);
                String description = jsonNode.path("description").asText();
                String imageUrl = gateway + "/microimage/images/" + jsonNode.path("fileName").asText() + "/get";
                imageVOs.add(new ImageVO(description, imageUrl));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return imageVOs;
    }
}

   
   
  
  
          
  • URL的構成為:”https://”+注冊在Eureka上的服務名稱+調用的接口名(http://MICROIMAGE/images/getAll
  • 根據接口支持的http方法的不同,使用RestTemplate提供的不同方法,比如對get接口使用getForObject,post接口使用postForObject
  • 使用ObjectMapper轉換接口返回的json數據


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM