SpringBoot 使用RestTemplate实现调用服务

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

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

准备工作

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



   org.springframework.boot
   spring-boot-starter-web




    org.apache.httpcomponents
    httpclient
    4.5.5

 注入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 entity = new HttpEntity<>(userEntity);
        ResponseEntity 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 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 ResponseEntity

           exchange(String url, HttpMethod method, @Nullable HttpEntity requestEntity, Class responseType) 

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

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

SpringBoot 使用RestTemplate实现调用服务_第1张图片

SpringBoot 使用RestTemplate实现调用服务_第2张图片

 

 

   

你可能感兴趣的:(Java,SpringBoot)