SpringCloud-Netflix学习笔记02——用RestTemplate建立服务提供者和服务消费者之间的通信
前言
服务提供者和服务消费者之间通过Rest进行通信,消费者可以通过SpringBoot提供的RestTemplate类来获取提供者提供的服务,以达到自身目的。
准备
首先搭建服务提供者的环境,就是简单的一个web后端项目(前后端分离),由Dao、Service、Controller三层组成,Controller层使用 @RestController
进行通信。
服务消费者配置
1、导入依赖
消费者必须要导入 spring-boot-starter-web
依赖,版本随 spring-boot-dependencies
。
<!--SpringBoot 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.3.12.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2、将RestTemplate注入Spring
编写一个配置类 ConfigBean
,将RestTemplate注入到Spring中。
@Configuration
public class ConfigBean {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
3、调用服务提供者提供的服务
消费者不应该有service层,通过RestTemplate去远程调用提供者提供的service或者服务。所以我们直接写Controller层代码。
首先自动装配 RestTemplate
。
@Autowired
private RestTemplate restTemplate;
接下来就可以编写接口了,按照自己需要实现的功能编写对应的接口函数,例如:
private static final String REST_URL_PREFIX = "http://localhost:8001";
@RequestMapping("/dept/get/{id}")
public Dept queryDeptById(@PathVariable("id") Long id){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/queryDeptById/"+id, Dept.class);
}
其中 restTemplate.getForObject(REST_URL_PREFIX+"/dept/queryDeptById/"+id, Dept.class)
,是通过restTemplate类来调用服务提供者提供的服务,直接通过接口URl调用,十分方便。
restTemplate.getForObject
形参如下:
RestTemplate.getForObject(url, 实体:Map(参数), Class<T> responseType(返回类型))
其中参数传递有三种方法:
参数可以直接用url传,或者直接传一个实体类,或者用map封装
全部代码如下:
@RestController
@RequestMapping("/consumer")
public class DeptConsumerController {
//消费者不应该有service层,通过RestTemplate去远程调用提供者提供的service或者服务
//RestTemplate(url, 实体:Map(参数), Class<T> responseType(返回类型))
//参数可以直接用url传,或者直接传一个实体类,或者用map封装
@Autowired
private RestTemplate restTemplate;
private static final String REST_URL_PREFIX = "http://localhost:8001";
@RequestMapping("/dept/get/{id}")
public Dept queryDeptById(@PathVariable("id") Long id){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/queryDeptById/"+id, Dept.class);
}
@RequestMapping("/dept/add")
public boolean add(Dept dept){
return restTemplate.postForObject(REST_URL_PREFIX+"/dept/add", dept, Boolean.class);
}
@RequestMapping("/dept/queryAllDept")
public List<Dept> queryAllDept(){
return restTemplate.getForObject(REST_URL_PREFIX+"/dept/queryAllDept",List.class);
}
}
4、测试
分别启动服务提供者和服务消费者,在浏览器中访问消费者的接口,可以发现消费者调用提供者的服务成功!
分类:
spring家族
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)