restTemplate实现跨服务请求

RestTemplate实现跨服务请求

1. 前言

通常在多模块开发中,需要调用其他模块的服务。例如支付模块Payment,用户模块Consumer,用户模块需要调用支付模块的某些功能。此时两个模块分别运行在不同的端口上,前者8001,后者80。RestTemplate可以实现该功能

2. 实现

2.1 导依赖

版本version标签选择适合自己的

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2.2 加Bean

RestTemplate为第三方bean,同样的套路

@Configuration
public class ApplicationContextConfig {

  	/**
  	* 这样IOC容器中会有一个RestTemplate对象
  	/
    @Bean
    public RestTemplate getRestTemplate() {
        return new RestTemplate();
    }
}

2.3 调用方法

被调用模块

此时支付模块运行在8001端口上,项目运行起来

下面是payment模块的控制器

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @PostMapping("/create")
    public CommonResult create(Payment payment) {
        int result = paymentService.create(payment);
        log.info("插入结果:{}", result);
        if (result > 0) {
            return new CommonResult(CodeConstant.CODE_200, "插入数据库成功", result);
        } else {
            return new CommonResult(CodeConstant.CODE_444, "插入数据库失败", null);
        }
    }
}

调用模块

Consumer模块调用上面的模块,使用postForObject进行url转发

@RestController
@RequestMapping("/consumer")
@Slf4j
public class OrderController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String PAYMENT_URL = "http://localhost:8001/payment";

    @PostMapping("/payment/create")
    public CommonResult create(Payment payment) {
        log.info("consumer create...");
        return restTemplate.postForObject(PAYMENT_URL + "/create", payment, CommonResult.class);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值