Spring Cloud笔记(15) 创建服务消费者,使用 RestTemplate 在微服务之间跨服务通信调用

上篇我创建了一个微服务,并且创建了很多接口,当作业务的服务提供者。

Spring Cloud笔记(14) Spring Cloud Eureka Client 注册微服务 。但是却没有消费者来消费。本文解决两个问题,再次创建一个微服务当作消费者,调用提供者的接口数据,其次学习跨服务调用接口的组件 RestTemplate

创建消费者微服务

这里很简单和 上篇 一样,只不过配置文件中的端口不能一样。这里就不再重复,已经创建好。

RestTemplate 使用

上面创建的服务,我将它当作消费者,用来调用提供者的接口。至于跨服务调用接口的组件是 RestTemplate

这里有个小知识,什么样的 URL 是 RESTFUL 风格的。

  • 非 RESTful 的 URL:http://…../queryUserById?id=1
  • RESTful 的 URL:http://…./queryUserById/1

RestTemplate 是 Spring 框架提供的基于 REST 的服务组件,我这里直接使用,感觉看起来挺简单的,只是其中一些细节容易忘记。

1、先在 ConsumerApplication 中代码修改成如下。

@SpringBootApplication
public class ConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class,args);
    }

    /**
     * 创建 RestTemplate 实例并通过 @Bean 注解注入到 IoC 容器中
     * @return
     */
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

2、创建有关 Student 的 Controller ,用来调用 StudentProvider 的服务。

@RequestMapping("/consumer")
@RestController
public class StudentController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/findAll")
    public Collection<Student> findAll(){
        return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
    }

    @GetMapping("/findById/{id}")
    public Student findById(@PathVariable("id") long id){
        return restTemplate.getForObject("http://localhost:8010/student/findById/{id}",Student.class,id);
    }

    @PostMapping("/save")
    public void save(@RequestBody Student student){
        restTemplate.postForObject("http://localhost:8010/student/save",student,Student.class);
    }

    @PutMapping("/update")
    public void update(@RequestBody Student student){
        restTemplate.put("http://localhost:8010/student/update",student);
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteById(@PathVariable("id") long id){
        restTemplate.delete("http://localhost:8010/student/deleteById/{id}",id);
    }
}

这里稍微注意 RestTemplate 就是了

3、全部关闭,依次启动注册中心、服务提供者、服务消费者。

再调用服务器消费者的接口,服务消费者会通过RestTemplate调用服务提供的服务。

以上代码笔记内容来自付费专栏:案例上手 Spring 全家桶

PS:如果侵犯版权,请联系我。

 

本文由老郭种树原创,转载请注明:https://guozh.net/spring-cloud-resttemplate/

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注