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
本文介绍如何跨服务调用后端接口,包含三种方式:
- 从前端使用AJAX调用后端接口
- 在后端使用HttpURLConnection访问接口
- 在后端配合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微服务之跨服务调用后端接口的更多相关文章
- axios解决调用后端接口跨域问题
vue-cli通过是本地代理的方式解决接口跨域问题的.但是在vue-cli的默认项目配置中这个代理是没有配置的,如果现在项目中使用,必须手动配置config/index.js文件 ... proxyT ...
- jquery中的jsonp跨域调用(接口)
jquery jsonp跨域调用接口
- Nginx解决前端调用后端接口跨域问题
1.项目中遇到的问题描述: 前端调用zuul统一网关服务接口,请求状态码200,但是无返回数据. 浏览器控制台报错信息:No Access-Control-Allow-Origin header i ...
- 使用javascript把图片转成base64位编码,然后传送到服务端(ajax调用的接口基于drupa7)
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- 前端调用后端接口下载excel文件的几种方式
今天有一个导出相应数据为excel表的需求.后端的接口返回一个数据流,一开始我用axios(ajax类库)调用接口,返回成功状态200,但是!但是浏览器没有自动下载excel表,当时觉得可能是ajax ...
- 前端调用后端接口返回200(成功状态码),后端有返回,但是控制台Network Response为空,没展示任何信息
解决方法: 1.在js里面debugger,可以看到后台是否有返回数据. 2.直接console.log(),直接把返回值打印出来,查看返回的数据格式,方便前端进行数据的处理. PS:因为后端返回的数 ...
- 解决Vue调用springboot接口403跨域问题
最近在做一个前后端分离的项目, 前端用的是Vue后端使用的是springboot, 在项目整合的时候发现前端调用后端接口报错403跨域请求问题 前端跨域请求已解决, 那么问题就出在后端了, 找了一些资 ...
- express:webpack dev-server开发中如何调用后端服务器的接口?
开发环境: 前端:webpack + vue + vue-resource,基于如下模板创建的开发环境: https://github.com/vuejs-templates/webpack ...
- nginx解决跨域(前后端分离)
Nginx解决跨域问题 后端接口 请求地址 返回数据(json数据) http://127.0.0.1:8080//app Hello World! 前端代码 通过nginx做静态资源服务器访问端口8 ...
随机推荐
- Game HDU - 3657(最小割)
Game Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- 【XSY2760】nonintersect 计算几何
题目描述 平面上有\(n\)条线段,你要擦掉所有线段但保留原有的\(2n\)个端点,然后连接这些端点形成\(n\)条不相交的线段,每个端点只能在一条线段中. 假设你画的线段总长为\(Y\),原有线段的 ...
- windows 服务器同步互联网时间
@echo off ::netsh ipsec static set policy name=7road assign=n net time /setsntp:pool.ntp.org net sto ...
- Leetcode 215. 数组中的第K个最大元素 By Python
在未排序的数组中找到第 k 个最大的元素.请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素. 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 输出: 5 ...
- 「SCOI2016」美味 解题报告
「SCOI2016」美味 状态极差无比,一个锤子题目而已 考虑每次对\(b\)和\(d\)求\(c=d \ xor \ (a+b)\)的最大值,因为异或每一位是独立的,所以我们可以尝试按位贪心. 如果 ...
- HDU 5950 Recursive sequence(矩阵快速幂)
题目链接:Recursive sequence 题意:给出前两项和递推式,求第n项的值. 题解:递推式为:$F[i]=F[i-1]+2*f[i-2]+i^4$ 主要问题是$i^4$处理,容易想到用矩阵 ...
- LOJ#6284. 数列分块入门 8
分块的时候开一个数组标记这个区间是不是都是一样颜色的部分,如果是的话,我后面的查询,更新部分就可以直接整块操作,对于不是不全部都一样颜色的块在具体进到快里面去暴力. 在更新的时候对边上的两个不完整的块 ...
- http_proxy_module模块常用参数
Nginx的upstream模块相当于是建立一个函数库一样,把后端的服务器地址放在了一个池子里,而proxy模块则是从这个池子里调用了这些服务器. http_proxy_module模块常用参数: p ...
- 课后选做题:MyCP
目录 CP命令了解 MyCP实现 CP命令了解 作用:cp指令用于复制文件或目录,如同时指定两个以上的文件或目录,且最后的目的地是一个已经存在的目录,则它会把前面指定的所有文件或目录复制到此目录中.若 ...
- Gym - 100989E
Islam is usually in a hurry. He often types his passwords incorrectly. He hates retyping his passwor ...