RestTemplate 介绍

RestTemplate 是 Spring 提供的用于访问 Rest 服务的客户端,RestTemplate 提供了多种便捷访问远程 Http 服务的方法,能够大大提高客户端的编写效率。

服务消费者实现

业务需求说明

实现:通过红包系统访问订单系统,获得某个用户的订单信息,派发红包.

red-sys:服务的消费者

Order-sys:服务的提供者

red-sys 给 order-sys 的 Controller 发送 http 请求

创建 red-sys 项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.bjsxt</groupId>
<artifactId>red-sys</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging> <properties>
<!-- spring 依赖 -->
<spring.version>4.3.18.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<servlet-api.version>2.5</servlet-api.version>
<jsp-api.version>2.0</jsp-api.version>
<jackson.version>2.9.0</jackson.version>
</properties> <dependencies>
<!-- jsp相关依赖 -->
<!-- servlet依赖 -->
<!-- jstl依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<finalName>red</finalName>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/red</path>
<port>8080</port>
</configuration>
</plugin> </plugins>
</build>
</project>

Order实体类:

package com.bjsxt.pojo;

public class Order {
private int id;
private Double total;
private String date; public Order(int id, Double total, String date) {
this.id = id;
this.total = total;
this.date = date;
}
public Order(){} @Override
public String toString() {
return "Order{" +
"id=" + id +
", total=" + total +
", date='" + date + '\'' +
'}';
} public int getId() {
return id;
} public void setId(int id) {
this.id = id;
} public Double getTotal() {
return total;
} public void setTotal(Double total) {
this.total = total;
} public String getDate() {
return date;
} public void setDate(String date) {
this.date = date;
}
}

创建 RedController

package com.bjsxt.controller;

import com.bjsxt.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import java.util.Arrays;
import java.util.List;
import java.util.Map; @Controller
public class RedController {
//注入由spring提供的RestTemplate对象
@Autowired
RestTemplate restTemplate; @RequestMapping("/loadOrderList")
@ResponseBody
public List<Order> loadOrderList01(String uid){
//发送远程http请求URL
String url="http://localhost:7070/order/loadOrderList";
//发送到远程服务参数
MultiValueMap<String,Object> params=new LinkedMultiValueMap<>();
params.add("uid",uid);
//通过RestTemplate对象发送远程post请求
Order[] orders = restTemplate.postForObject(url, params, Order[].class);
return Arrays.asList(orders);
} //获得订单对象的集合
@RequestMapping("/loadOrderList2")
@ResponseBody
public List<Order> loadOrderList02(String uid){
//发送远程http请求URL
String url="http://localhost:7070/order/loadOrderList2";
//发送到远程服务参数
MultiValueMap<String,Object> params=new LinkedMultiValueMap<>();
params.add("uid",uid);
//通过RestTemplate对象发送远程post请求
ResponseEntity<Order[]> entity = restTemplate.postForEntity(url, params, Order[].class); //获取响应头信息
HttpHeaders headers = entity.getHeaders();
//遍历
for (Map.Entry<String,List<String>> e:headers.entrySet()) {
System.out.println(e.getKey()+"------"+e.getValue());
} //获取响应的状态
int status=entity.getStatusCodeValue();
System.out.println(status); //获取远程对象的响应实体
Order[] body = entity.getBody();
return Arrays.asList(body);
}
}

配置 springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller -->
<context:component-scan base-package="com.bjsxt.controller" /> <mvc:annotation-driven></mvc:annotation-driven> <!-- 实例化RestTemplate对象 -->
<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"></bean>
</beans>

配置 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>order</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list> <servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>/favicon.ico</url-pattern>
</servlet-mapping> <!-- 以监听器的方式启动spring容器 -->
<!-- <listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>--> <!-- &lt;!&ndash; 指定spring的配置文件 &ndash;&gt;
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-*.xml</param-value>
</context-param>--> <!-- POST请求的乱码过滤器 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 指定编码方式 -->
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<!-- 映射filter -->
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- springmvc的servlet -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 指定springmvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 让springmvc随系统启动而启动 -->
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

创建 order-sys 项目

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.bjsxt</groupId>
<artifactId>order-sys</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- spring 依赖 -->
<spring.version>4.3.18.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<servlet-api.version>2.5</servlet-api.version>
<jsp-api.version>2.0</jsp-api.version>
<jackson.version>2.9.0</jackson.version>
</properties> <dependencies>
<!-- jsp相关依赖 -->
<!-- servlet依赖 -->
<!-- jstl依赖 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servlet-api.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-api.version}</version>
<scope>provided</scope>
</dependency>
<!-- springmvc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
<scope>runtime</scope>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
</dependencies>
<build>
<finalName>order</finalName>
<plugins>
<!-- 配置Tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/order</path>
<port>7070</port>
</configuration>
</plugin> </plugins>
</build>
</project>

创建 OrderController

package com.bjsxt.controller;

import com.alibaba.fastjson.JSON;
import com.bjsxt.pojo.Order;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; @Controller
public class OrderController { @RequestMapping("/loadOrderList")
public String loadOrderList(String uid, Model mode){
Date now =new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(now); Order order1=new Order();
order1.setId(1001);
order1.setTotal(123.0);
order1.setDate(date); Order order2=new Order();
order2.setId(1002);
order2.setTotal(1234.0);
order2.setDate(date); Order order3=new Order();
order3.setId(1003);
order3.setTotal(13.0);
order3.setDate(date); List<Order> list=new ArrayList<>();
list.add(order1);
list.add(order2);
list.add(order3); mode.addAttribute("list",list);
return "index.jsp";
} //接收http请求,响应订单集合,完成的是异步响应 将List集合序列化为json串响应
@RequestMapping("/loadOrderList2")
@ResponseBody
public List<Order> loadOrderList2(String uid, Model mode){
System.out.println("uid="+uid); Date now =new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(now); Order order1=new Order();
order1.setId(1001);
order1.setTotal(123.0);
order1.setDate(date); Order order2=new Order();
order2.setId(1002);
order2.setTotal(1234.0);
order2.setDate(date); Order order3=new Order();
order3.setId(1003);
order3.setTotal(13.0);
order3.setDate(date); List<Order> list=new ArrayList<>();
list.add(order1);
list.add(order2);
list.add(order3); mode.addAttribute("list",list);
return list;
} @RequestMapping("/loadOrderList3")
@ResponseBody
public String loadOrderList3(String uid, String callback){
System.out.println("uid="+uid); Date now =new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
String date = sdf.format(now); Order order1=new Order();
order1.setId(1001);
order1.setTotal(123.0);
order1.setDate(date); Order order2=new Order();
order2.setId(1002);
order2.setTotal(1234.0);
order2.setDate(date); Order order3=new Order();
order3.setId(1003);
order3.setTotal(13.0);
order3.setDate(date); List<Order> list=new ArrayList<>();
list.add(order1);
list.add(order2);
list.add(order3); String result=callback+"("+ JSON.toJSONString(list) +")";
return result;
}
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<c:forEach items="${list }" var="o">
${o.id}----${o.total}----${o.date}
<hr/>
</c:forEach>
</body>
</html>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 扫描controller -->
<context:component-scan base-package="com.bjsxt.controller" /> <mvc:annotation-driven></mvc:annotation-driven>
</beans>

启动 order-sys

启动访问 red-sys

使用 Spring 提供的 restTemplate 完成 Http 服务消费的更多相关文章

  1. Spring提供的用于访问Rest服务的客户端:RestTemplate实践

    什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...

  2. Spring Cloud Alibaba 使用Feign进行服务消费

    为什么使用Feign? Feign可以把Rest的请求进行隐藏,伪装成类似SpringMVC的Controller一样.你不用再自己拼接url,拼接参数等等操作,一切都交给Feign去做. 使用Fei ...

  3. 使用 RestTemplate 调用 restful 服务

    什么是RestTemplate? RestTemplate是Spring提供的用于访问Rest服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效 ...

  4. Spring Boot使用RestTemplate消费REST服务的几个问题记录

    我们可以通过Spring Boot快速开发REST接口,同时也可能需要在实现接口的过程中,通过Spring Boot调用内外部REST接口完成业务逻辑. 在Spring Boot中,调用REST Ap ...

  5. Spring Cloud(三):服务提供与调用 Eureka【Finchley 版】

    Spring Cloud(三):服务提供与调用 Eureka[Finchley 版]  发表于 2018-04-15 |  更新于 2018-05-07 |  上一篇文章我们介绍了 Eureka 服务 ...

  6. Spring Cloud Alibaba 使用RestTemplate进行服务消费

    创建服务提供者工程 创建spring-cloud-alibaba-service-member工程,会员中心服务该服务提供用户会员信息. pom.xml <?xml version=" ...

  7. Spring Cloud Alibaba基础教程:支持的几种服务消费方式(RestTemplate、WebClient、Feign)

    通过<Spring Cloud Alibaba基础教程:使用Nacos实现服务注册与发现>一文的学习,我们已经学会如何使用Nacos来实现服务的注册与发现,同时也介绍如何通过LoadBal ...

  8. 【译文】用Spring Cloud和Docker搭建微服务平台

    by Kenny Bastani Sunday, July 12, 2015 转自:http://www.kennybastani.com/2015/07/spring-cloud-docker-mi ...

  9. spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法

    spring boot / cloud (十四) 微服务间远程服务调用的认证和鉴权的思考和设计,以及restFul风格的url匹配拦截方法 前言 本篇接着<spring boot / cloud ...

随机推荐

  1. day7-format字符串格式化

    tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18) print ...

  2. maven安装与在eclipse中配置

    需要准备 eclipse maven压缩包 : http://maven.apache.org/download.cgi 1 解压maven压缩包 2 在系统变量中新建变量MAVEN_HOME,值为 ...

  3. python——多线程

    多线程特点: • 线程的并发是利用cpu上下文的切换(是并发,不是并行) • 多线程执行的顺序是无序的 • 多线程共享全局变量 • 线程是继承在进程里的,没有进程就没有线程 • GIL全局解释器锁 • ...

  4. H5+app -- 关于ajax提交问题

    1.前阵子在做系统的h5+ app为满足手机端也能进行业务操作,例如:提货,扫描入库之类的.所以就要将做接口,从手机端调用后台系统的方法. 2.例如这样的请求格式,但是呢,每次请求它都直接跳到erro ...

  5. AngularJS: Error reports on $injector:modulerr

    Angular JS最常见的问题是,程序启动失败,error为$injector:modulerr 错误是因为加载对应的Module失败,但很难找到需要修改的Module. 一个简单的小技巧是,不要使 ...

  6. nyoj 274-正三角形的外接圆面积 (R = PI * a * a / 3)

    274-正三角形的外接圆面积 内存限制:64MB 时间限制:1000ms 特判: No 通过数:14 提交数:22 难度:0 题目描述: 给你正三角形的边长,pi=3.1415926 ,求正三角形的外 ...

  7. 802.11r协议理解

    首先阅读了相关协议内容整理出了如下的802.11r时序图所谓基础,然后会详细理解其中的每一个步骤:

  8. 编写 Dockerfile 最佳实践

    官方仓库虽然有数十万计的免费镜像,但大多数无法直接满足公司业务需求,这就需要我们自己去定制镜像了. Docker通过Dockerfile自动构建镜像,Dockerfile是一个包含用于组建镜像的文本文 ...

  9. C语言I博客作业09

    问题 答案 这个作业的属于那个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/SE2019-4/homework/10034 我 ...

  10. docker入门篇

    在网上的教程中,大多数是建议利用linux来安装docker,在此我也建议大家用linux安装,为什么?请看下图 docker使用go语言开发,并且运行在linux系统下,而如果想用window运行, ...