This is the 21st day of my participation in the August More Text Challenge

In the actual process of developing projects using SpringBoot, back-end services often encounter cross-module access requirements, which requires the same development specification of our service interfaces, so that cross-module invocation can be more convenient and efficient. Spring Boot also provides very powerful componentization support for creating Web services, which is simple and convenient. Let’s take a look.

SpringBoot implements RESTful interfaces

RESTful services

Representational State Transfer is a popular representation of Web services in distributed systems and microservice architectures. Representational State Transfer is essentially an architectural style rather than a specification.

RESTful architecture treats server access as a Resource. Each Resource is identified with a unique address using a Universal Resource Identifier (URI) and uses standard HTTP methods over transport protocols. Such as GET, PUT, POST, and DELETE.

Service related notes

Enter notes

  • @GetMapping/@PostMapping/@PutMapping/@DeleteMapping('/')Spring Boot2 introduces a RESTful request annotation followed by a specific request path, which is equivalent to the @requestMapping annotation and uses HTTP methods such as requestMethod.get by default.
  • @RequestMapping('/'): Followed by the URL, you can specify the specific path of the interface. You can specify path information, request mode, and content type
    1. The @requestMapping annotation defines the root path of the service at the service level (controller class). It is usually plural “/accounts”
    2. The @getMapping annotation defines the path and parameter information of the HTTP request method at the operation level
    3. When making HTTP requests, the content-Type attribute can be used to specify the type of content to be transmitted@RequestMappingIn the annotationsproducesProperty to set the property.
      @RequestMapping(value = "accounts", produces="application/json")
      Copy the code
  • @PathVariable: This annotation is used to get the path parameter fromurl/{id}This form is obtained in the path{id}The value of the parameter
    @GetMapping(value = "/{id}")
    public Account getAccountById(@PathVariable("id") String id) {
        Account account = accountService.getAccountById(id);
        return account;
    }
    Copy the code
  • @RequestParam: The role of annotations and@PathVariableAnnotation similar, also used to get the parameters in the request, oriented similarurl? id=XXIn the form.
  • @RequestBody: annotation is used for processingcontent-typeforapplication/jsonType when encoding content, through@RequestBodyAnnotations bind the JSON string in the request body to the appropriate Javabeans.
@PostMapping(value = "/")
public void updateAccount(@RequestBody Account account) {... }Copy the code

Output annotations

@RestController: This annotation is equivalent to the @Controller and @responseBody annotations in Spring MVC, which automatically return JSON data. When used, we only need to return a plain business object because the @RestController annotation hides the complexity of the underlying implementation.

Use RestTemplate to access the RESTful interface of the HTTP endpoint

Service creation is completed, we will service for consumer, access RESTful services provided by the RestTemplate is SpringBoot client class template tool, located in the org. Springframework. Web. The client package.

Create the RestTemplate object

The most common way to create a RestTemplate object is to simply new an instance:

@Bean
public RestTemplate restTemplate(a){
    return new RestTemplate();
}
Copy the code

The RestTemplate class has one constructor with no arguments and one with arguments. The default is to use the constructor with no arguments, which can be used to enhance some functionality.

// The no-argument constructor adds a bunch of HttpMessageConverter objects for message transformation
public RestTemplate(a) {
        this.messageConverters.add(new ByteArrayHttpMessageConverter());
        this.messageConverters.add(new StringHttpMessageConverter());
        this.messageConverters.add(new ResourceHttpMessageConverter(false));
        this.messageConverters.add(new SourceHttpMessageConverter<>());
        this.messageConverters.add(new AllEncompassingFormHttpMessageConverter());
 
        // Omit other code to add HttpMessageConverter
}

// A ClientHttpRequestFactory interface can be set. The various implementation classes based on this interface provide fine-grained control over the behavior in the RestTemplate, such as setting properties such as the timeout of HTTP requests.
public RestTemplate(ClientHttpRequestFactory requestFactory) {
        this(a); setRequestFactory(requestFactory); }Copy the code

Use RestTemplate to access the Web service

  • GET method: includes getForObject and getForEntity
  • POST methods: In addition to postForObject and postForEntity, postForLocation methods are provided
  • PUT mode: PUT method
  • DALETE mode: Delete method
  • Header method: headForHeaders method
  • There are no restrictions: Exchange and execute methods are included. Exchange is a universal and unified method that can be used to send GET and POST requests, as well as various other types of requests.

The last

Using RESTful interfaces in SpringBoot to unify interface specifications makes our development more standardized and uses the RestTemplate consumer interface.

The RestTemplate template class for accessing remote HTTP endpoints provides developers with a number of useful utility methods for sending HTTP requests and getting responses. RestTemplate is an effective tool class in terms of design and implementation, with custom entry points for developers to embed to implement fine-grained processing logic for managing HTTP requests.