RestTemplate的简单使用


RestTemplate的简单使用

RestTemplate是httpclient的封装,提供了多种便捷访问远程Http服务的方法,是一种简单便捷的访问restful服务模板类,是Spring提供的用于访问Rest服务的客户端模板工具集,类似于jdbcTemplate、redisTemplate

使用restTemplate访问restful接口很简单:

(url,requestMap,ResponseBean.class)这三个参数分别代表rest请求地址、请求参数、htt响应被转换成的对象类型

案例:

编写配置类,将RestTemplate对象放入spring容器

package com.yl.order.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * RestTemplate配置类
 *
 * @auther Y-wee
 */
@Configuration
public class ApplicationContextConfig {

    @Bean
    // 开启默认负载均衡
    @LoadBalanced
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }

}

在controller中使用RestTemplate调用远程服务

package com.yl.order.controller;


import com.yl.common.entity.CommonResult;
import com.yl.common.entity.Payment;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 订单
 *
 * @auther Y-wee
 */
@RequestMapping("/order")
@RestController
@Slf4j
public class OrderController {
    @Resource
    private RestTemplate restTemplate;

    // 被调用服务的URL
//    public static final String PAYMENT_URL = "http://localhost:8001";
    /**
     * 当被调用的服务注册了多个服务实例时,通过注册的服务名来调用,URL不能写死,
     * 同时RestTemplate需要开启负载均衡告诉客户端调用哪个端口的服务
     */
    public static final String PAYMENT_URL = "http://PAYMENT";

    /**
     * 添加数据
     *
     * @param payment payment
     * @return 添加结果
     */
    @GetMapping("/postForObject/payment/create")
    public CommonResult postForObject(Payment payment) {
        // 发送post请求,返回对象为响应体中数据转化成的对象,基本上可以理解为json
//        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        return restTemplate.postForObject(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
    }

    /**
     * 添加数据
     *
     * @param payment payment
     * @return 添加结果
     */
    @GetMapping("/postForEntity/payment/create")
    public CommonResult postForEntity(Payment payment) {
        // 发送post请求,返回对象为ResponseEntity,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等
        ResponseEntity entity = restTemplate.postForEntity(PAYMENT_URL + "/payment/create", payment, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }

    /**
     * 查询数据
     *
     * @param id id
     * @return 查询结果
     */
    @GetMapping("/getForObject/payment/get/{id}")
    public CommonResult getForObject(@PathVariable("id") Long id) {
        // 发送get请求
        return restTemplate.getForObject(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
    }

    /**
     * 查询数据
     *
     * @param id id
     * @return 查询结果
     */
    @GetMapping("/getForEntity/payment/get/{id}")
    public CommonResult getForEntity(@PathVariable("id") Long id) {
        // 发送get请求
        ResponseEntity entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
        if (entity.getStatusCode().is2xxSuccessful()) {
            return entity.getBody();
        } else {
            return new CommonResult<>(444, "操作失败");
        }
    }
}

被调用服务的controller

package com.yl.payment.controller;

import com.yl.common.entity.CommonResult;
import com.yl.common.entity.Payment;
import com.yl.payment.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 支付
 *
 * @auther Y-wee
 */
@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {
    @Resource
    private PaymentService paymentService;
    @Value("${server.port}")
    private String serverPort;

    /**
     * 添加数据
     *
     * @param payment payment
     * @return 添加结果
     */
    @PostMapping(value = "/create")
    public CommonResult create(@RequestBody Payment payment) {
        int result = paymentService.create(payment);
        if (result > 0) {
            return new CommonResult(200, "插入数据库成功:"+serverPort, result);
        }
        return new CommonResult(444, "插入数据库失败", null);
    }

    /**
     * 查询数据
     *
     * @param id id
     * @return 查询结果
     */
    @GetMapping(value = "/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment payment = paymentService.getPaymentById(id);
        if (payment != null) {
            return new CommonResult(200, "查询成功:"+serverPort, payment);
        }
        return new CommonResult(444, "没有对应记录,查询ID: " + id, null);
    }

}