Spring Cloud (4): Use of RestTemplate

In the previous article, we have learned how to create a service provider, so in this article we will create a service consumer. The implementation idea is to build a microservice application through Spring boot, and then register it to the registration center Eureka through Eureka Client Server, becomes a service consumer. So how does the service consumer call the interface of the service provider? Then we first introduce the use of a component RestTemplate.

1. What is RestTemplate

RestTemplate is a REST-based service component provided by the Spring framework. The underlying layer encapsulates HTTP requests and responses, and provides many methods for accessing RETS services, which can simplify code development.

2. How to use RestTemplate

  1. Create a maven project as a subservice
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    <version>2.0.2.RELEASE</version>
</dependency>
  1. Create application.yml, the code is as follows
server:
  port: 8080
spring:
  application:
    name: consumer
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true
  1. Create the same entity class as the service provider, the code is as follows
package com.frr.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data //生成Getter,Setter,equals,canEqual,hasCode,toString等方法
@AllArgsConstructor //添加一个构造函数,该构造函数含有所有已声明字段属性参数
@NoArgsConstructor //创建一个无参构造函数
public class Student {
    
    
	private long id;
	private String name;
	private int age;
}
  1. Create a controller, and call the interface of the service provider in the method, the code is as follows
package com.frr.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.frr.entity.Student;

@RestController
@RequestMapping("/consumer")
public class RestTemplateController {
    
    
	
	@Autowired
	private RestTemplate restTemplate;
	
	@GetMapping("/findAll")
	@SuppressWarnings("unchecked")
	public Collection<Student> findAll(){
    
    
		return restTemplate.getForEntity("http://localhost:8010/student/findAll", Collection.class).getBody();
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/findAll2")
	public Collection<Student> findAll2(){
    
    
		return restTemplate.getForObject("http://localhost:8010/student/findAll",Collection.class);
	}
	
	@GetMapping("/findById/{id}")
	public Student findById(@PathVariable("id") long id){
    
    
		return	restTemplate.getForEntity("http://localhost:8010/student/findById/{id}",Student.class,id).getBody();
	}
	
	@GetMapping("/findById2/{id}")
	public Student findById2(@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.postForEntity("http://localhost:8010/student/save",student,null).getBody();
	}
	
	@PostMapping("/save2")
	public void save2(@RequestBody Student student){
    
    
		restTemplate.postForObject("http://localhost:8010/student/save",student,null);
	}
		
	@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);
	}
	
}
  1. To create a startup class, it should be noted that the instance of RestTemplate needs to be injected into the startup class. Here, the method of @Bean is used, and the code is as follows
package com.frr;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApplication {
    
    
	public static void main(String[] args) throws Exception {
    
    
		SpringApplication.run(RestTemplateApplication.class, args);
	}
	
	@Bean
	public RestTemplate restTemplate(){
    
    
		return new RestTemplate();
	}
}
  1. Start the registration center, service provider, and service consumer in turn, and use the Postman tool to test. Different requests can get the same data back

    • 8010 Service provider findAll interface returns data as follows

insert image description here

  • The data returned by the 8080 service consumer findAll interface is as follows
    insert image description here
  • Conclusion: The data returns are consistent, and the service consumer successfully calls the service provider's interface!

6. Summary

From the perspective of code, there is not much difference between service providers and service consumers. They are all Spring boot projects. On this basis, we let them have different identities through some components of Spring Cloud. . The service provider provides an interface for external access, and the service consumer also provides an interface for external access, but the interface is an interface for calling other services, so in a sense, the service consumer is also a service provider. Other services can also consume services from service consumers. Therefore, there is no absolute provider and consumer between services, and they can call each other!

In the microservice architecture, there will be many services, so we need to have a unified access portal, so how do we achieve it, let us look forward to the next article

One development engineer is also in the continuous learning stage, and the usual small experiences are shared from time to time. I hope that those who read the text I wrote can avoid detours and wish you success in work and study.
Bloggers have limited experience, if there are any shortcomings, welcome to communicate and improve together~ I hope to make progress together with you who are also in CSDN.

Author | Sweet Little Sweet Potato
Produced | Little Sweet Potato

Guess you like

Origin blog.csdn.net/qq_36836370/article/details/130871312