RestTemplate

RestTemplate

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

RestTemplate官网

需要一个配置类

package com.fujiew.springcloud.config;

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

/**
 * @author fujiew
 * @version v1.0.0
 * @Package : com.fujiew.springcloud.config
 * @Description : TODO
 * @Create on : 2020/9/11 11:00
 **/
@Configuration
public class ApplicationContextConfig {
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

使用

@RestController
@Slf4j
public class PaymentController {

    @Resource
    private PaymentService service;

    @PostMapping(value = "payment/create")
    public CommonResult<Object> create(@RequestBody Payment payment) {
        int result = service.create(payment);
        log.info("插入结果*****" + result);
        if (result > 0) {
            return new CommonResult<>(200, "插入成功", payment);
        } else {
            return new CommonResult<>(404, "插入失败", null);
        }
    }

    @GetMapping(value = "payment/get/{id}")
    public CommonResult<Object> getPaymentById(@PathVariable("id") Long id) {
        Payment payment = service.getPaymentById(id);
        log.info("查询结果" + payment);
        if (payment != null) {
            return new CommonResult<>(200, "查询成功", payment);
        } else {
            return new CommonResult<>(404, "not found", null);
        }
    }
}

posted @ 2020-09-11 11:41  汪什么来着儿  阅读(232)  评论(0编辑  收藏  举报