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数据
原文地址:https://www.cnblogs.com/jpfss/p/10760913.html