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数据

SpringCloud微服务之跨服务调用后端接口的更多相关文章

  1. axios解决调用后端接口跨域问题

    vue-cli通过是本地代理的方式解决接口跨域问题的.但是在vue-cli的默认项目配置中这个代理是没有配置的,如果现在项目中使用,必须手动配置config/index.js文件 ... proxyT ...

  2. jquery中的jsonp跨域调用(接口)

                                                                           jquery jsonp跨域调用接口

  3. Nginx解决前端调用后端接口跨域问题

    1.项目中遇到的问题描述: 前端调用zuul统一网关服务接口,请求状态码200,但是无返回数据. 浏览器控制台报错信息:No  Access-Control-Allow-Origin header i ...

  4. 使用javascript把图片转成base64位编码,然后传送到服务端(ajax调用的接口基于drupa7)

    <!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...

  5. 前端调用后端接口下载excel文件的几种方式

    今天有一个导出相应数据为excel表的需求.后端的接口返回一个数据流,一开始我用axios(ajax类库)调用接口,返回成功状态200,但是!但是浏览器没有自动下载excel表,当时觉得可能是ajax ...

  6. 前端调用后端接口返回200(成功状态码),后端有返回,但是控制台Network Response为空,没展示任何信息

    解决方法: 1.在js里面debugger,可以看到后台是否有返回数据. 2.直接console.log(),直接把返回值打印出来,查看返回的数据格式,方便前端进行数据的处理. PS:因为后端返回的数 ...

  7. 解决Vue调用springboot接口403跨域问题

    最近在做一个前后端分离的项目, 前端用的是Vue后端使用的是springboot, 在项目整合的时候发现前端调用后端接口报错403跨域请求问题 前端跨域请求已解决, 那么问题就出在后端了, 找了一些资 ...

  8. express:webpack dev-server开发中如何调用后端服务器的接口?

    开发环境:     前端:webpack + vue + vue-resource,基于如下模板创建的开发环境: https://github.com/vuejs-templates/webpack  ...

  9. nginx解决跨域(前后端分离)

    Nginx解决跨域问题 后端接口 请求地址 返回数据(json数据) http://127.0.0.1:8080//app Hello World! 前端代码 通过nginx做静态资源服务器访问端口8 ...

随机推荐

  1. Shell 对整个文件夹中的文件进行MD5校验 [转]

    查看本地文件的 MD5 命令:md5sum FileName查看home目录下所有文件的 MD5 码:cd ~find /home -type f -print0 | xargs -0 md5sum ...

  2. Double.valueOf(0.0D) 分析

    private Double price = Double.valueOf(0.0D); 查看Java API 文档如下: doubleValue public double doubleValue( ...

  3. new 经典基础模板总结

    NOIP-NOI-ZJOI基础模板总结 目录 C++语言和STL库操作 重载运算符操作 /* 重载运算符 格式 如重载小于号 这里是以x递减为第一关键字比较,y递减为第二关键字比较 */ bool o ...

  4. django pymysql

    此处django版本为1.11.13 设置setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NA ...

  5. zabbix3.2添加web页面监控(Web monitoring)

    应用场景: 存在一种情况:nginx或者httpd服务本身运行正常,但是网页挂了,类似于网页被黑,或者40X之类的... 可以用zabbix把web页面访问也监控起来,第一时间得知web崩溃信息并做相 ...

  6. centos7破解安装confluence5.9.11

    应用环境:Confluence是一个专业的企业知识管理与协同软件,也可以用于构建企业wiki.通过它可以实现团队成员之间的协作和知识共享. 安装环境:centos7.3 Java环境 1.7.0_79 ...

  7. 牛客练习赛31 D神器大师泰兹瑞与威穆

    双链表搞完了 #include<bits/stdc++.h> using namespace std; #define maxn 1000005 int tot,bac[maxn],fa[ ...

  8. express框架学习笔记

    用express框架也有一段时间了,下面我总结一下我做项目时迷惑的点: app.use()与app.get()的区别 app.use()是用来为应用程序绑定中间件的,当第一个参数是path是,第二个参 ...

  9. semantic ui框架学习笔记二

    评论组件 文档里的评论组件介绍的比较清晰.这里我就挑一个我喜欢的格式展示出来: <div class="ui comments"> <h3 class=" ...

  10. JS怎么判断一个对象是否为空

    昨天面试的时候被问到的问题.只怪自己根基不牢,没有回答好 甚至说出了“判断这个obj是否和{}相等”这样鱼蠢的答案(/(ㄒoㄒ)/~~)引用类型怎么可以直接判断==或者===呢?! 今天中秋佳节,宝宝 ...