SpringCloud-Netflix学习笔记02——用RestTemplate建立服务提供者和服务消费者之间的通信
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
前言
服务提供者和服务消费者之间通过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、测试
分别启动服务提供者和服务消费者在浏览器中访问消费者的接口可以发现消费者调用提供者的服务成功