天天看点

SpringBoot 使用RestTemplate实现调用服务准备工作 注入RestTemplate 调用服务

SpringBoot的搭建可以看一下我之前写的一篇博客

https://blog.csdn.net/cwr452829537/article/details/81351987

准备工作

要使用RestTemplate需要引入依赖,web依赖也可以在创建项目时选择Web -> Web

<!-- web -->

<dependency>

   <groupId>org.springframework.boot</groupId>

   <artifactId>spring-boot-starter-web</artifactId>

</dependency>

<!-- 远程调用 httpclient -->

<dependency>

    <groupId>org.apache.httpcomponents</groupId>

    <artifactId>httpclient</artifactId>

    <version>4.5.5</version>

</dependency>

 注入RestTemplate

  首先需要在Application中加入一个RestTemplate

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

@SpringBootApplication
public class RemoteApplication {
    @Bean //必须new 一个RestTemplate并放入spring容器当中,否则启动时报错
    public RestTemplate restTemplate() {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(30 * 1000);
        httpRequestFactory.setConnectTimeout(30 * 3000);
        httpRequestFactory.setReadTimeout(30 * 3000);
        return new RestTemplate(httpRequestFactory);
    }
    public static void main(String[] args) {
        SpringApplication.run(RemoteApplication.class, args);
    }
}
           

 调用服务

  实体类

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
public class UserEntity {
    @JsonProperty("user_id")
    private Long userId;
    private String name;
    private String phone;
}
           
import lombok.Data;

@Data
public class Result {
    private Integer code;
    private String message;
}
           

  controller

import com.cwr.remote.model.db.UserEntity;
import com.cwr.remote.model.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


@RequestMapping("/remote")
//允许跨域访问
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
public class RemoteController {
    //自动注入RestTemplate 
    private final RestTemplate restTemplate;

    @Autowired
    public RemoteController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 调用远程服务添加用户信息
     *
     * @param userEntity 用户实体
     * @return
     */
    @PostMapping("/add-user")
    public Result addUser(@RequestBody UserEntity userEntity) {
        HttpEntity<UserEntity> entity = new HttpEntity<>(userEntity);
        ResponseEntity<Result> resultResponseEntity = this.restTemplate.exchange(
                "http://xxx.xxx.xxx.xxx/user/add",
                HttpMethod.POST, entity, Result.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }

    /**
     * 调用远程服务查询单个用户信息
     *
     * @param id 用户id
     * @return
     */
    @GetMapping("/find-user-id/{id}")
    public UserEntity findOne(@PathVariable Long id) {
        ResponseEntity<UserEntity> resultResponseEntity = this.restTemplate.exchange(
                String.format("http://xxx.xxx.xxx.xxx/user/find-id/%s", id),
                HttpMethod.GET, null, UserEntity.class);
        if (resultResponseEntity.getStatusCode() == HttpStatus.OK) {
            return resultResponseEntity.getBody();
        }
        return null;
    }
}
           

这里详细讲一下exchange( )方法

public <T> ResponseEntity<T>

           exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType) 

  •     url:请求地址,如果需要在url中带参数,使用String.format(),用%s拼接即可;
  •     method:请求方式,HttpMethod是一个枚举类型,有GET、POST、DELETE等方法;
  •     requestEntity:请求参数,这个主要是POST等有请求体的方法才需要,GET、DELETE等方法可以为null;
  •     responseType:返回数据类型。

测试结果(我使用的是Postman)

SpringBoot 使用RestTemplate实现调用服务准备工作 注入RestTemplate 调用服务
SpringBoot 使用RestTemplate实现调用服务准备工作 注入RestTemplate 调用服务