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、测试

  分别启动服务提供者和服务消费者,在浏览器中访问消费者的接口,可以发现消费者调用提供者的服务成功!

posted @ 2023-01-14 11:52  爱吃雪糕的小布丁  阅读(4)  评论(0编辑  收藏  举报  来源