Controller下的restTemplate路径问题

学SpringCloud的过程中出现了以下问题

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Thu May 19 20:38:34 CST 2022

There was an unexpected error (type=Internal Server Error, status=500).

404 : [{"timestamp":"2022-05-19T12:38:34.866+0000","status":404,"error":"Not Found","message":"No message available","path":"/payment/get31"}]

org.springframework.web.client.HttpClientErrorException$NotFound: 404 : [{"timestamp":"2022-05-19T12:38:34.866+0000","status":404,"error":"Not Found","message":"No message available","path":"/payment/get31"}]

原本的代码

@GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPayment(@PathVariable Long id){
        return restTemplate.getForObject(PAYMENT_URL+"/payment/get"+id,CommonResult.class,id);
    }

找了好久,发现错误是“/payment/get”后面少了一个反斜杠“/”,要改成如下

restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class,id);

纯粹是粗心。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在其他服务中非controller调用API网关中的服务,可以使用RestTemplate或Feign等工具来发起HTTP请求。 如果使用RestTemplate,可以在其他服务中创建一个RestTemplate实例,并使用该实例来发起HTTP请求。需要注意的是,由于API网关中可能会进行一些过滤、路由等操作,因此需要使用API网关中的服务地址来发起请求,而不是直接使用后端服务的地址。 下面是一个使用RestTemplate调用API网关服务的示例代码: ```java RestTemplate restTemplate = new RestTemplate(); String apiUrl = "http://api-gateway-service:8080/api/service"; ResponseEntity<String> response = restTemplate.getForEntity(apiUrl, String.class); String responseBody = response.getBody(); ``` 在上述代码中,我们创建了一个名为restTemplateRestTemplate实例,并使用该实例来发起GET请求。我们使用了API网关中的服务地址"http://api-gateway-service:8080/api/service"来发起请求,而不是直接使用后端服务的地址。 如果使用Feign,可以在其他服务中定义一个Feign接口,并使用该接口来发起HTTP请求。需要注意的是,需要使用@FeignClient注解来指定API网关中的服务名,并使用@RequestMapping注解来指定API网关中服务的请求路径。 下面是一个使用Feign调用API网关服务的示例代码: ```java @FeignClient(name = "api-gateway-service") public interface ApiService { @RequestMapping(method = RequestMethod.GET, value = "/api/service") String getService(); } ApiService apiService = Feign.builder() .encoder(new JacksonEncoder()) .decoder(new StringDecoder()) .target(ApiService.class, "http://api-gateway-service:8080"); String responseBody = apiService.getService(); ``` 在上述代码中,我们定义了一个名为ApiService的Feign接口,并使用@FeignClient注解指定了API网关中的服务名。我们使用@RequestMapping注解来指定API网关中服务的请求路径。最后,我们使用Feign.builder()方法创建一个Feign客户端实例,并使用该实例来发起请求。我们同样使用了API网关中的服务地址"http://api-gateway-service:8080"来发起请求,而不是直接使用后端服务的地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值