谷粒商城学习——P90 调用远程服务
在谷粒商城学习——P20-27springcloud alibaba课程中已经学过openfeign调用远程服务的基本示例,重复的不在赘述
被调用的远程controller接口指定了@PostMapping和@RequestBody,则调用的时候也需要指定这两个注解以保证签名一致
关键代码:
SpuBoundsController:接口提供方
@RestController @RequestMapping("coupon/spubounds") public class SpuBoundsController { @Resource private SpuBoundsService spuBoundsService; @PostMapping("/save") public R save(@RequestBody SpuBoundsEntity spuBounds){ spuBoundsService.save(spuBounds); return R.ok(); } }
CouponFeignService:调用方的接口,指定远程调用信息
@FeignClient("gulimall-coupon") public interface CouponFeignService { /** * 1、CouponFeignService.saveSpuBounds(spuBoundTo); * 1)、@RequestBody将这个对象转为json。 * 2)、找到gulimall-coupon服务,给/coupon/spubounds/save发送请求。 * 将上一步转的json放在请求体位置,发送请求; * 3)、对方服务收到请求。请求体里有json数据。 * (@RequestBody SpuBoundsEntity spuBounds);将请求体的json转为SpuBoundsEntity; * 只要json数据模型是兼容的。双方服务无需使用同一个to */ @PostMapping("/coupon/spubounds/save") R saveSpuBounds(@RequestBody SpuBoundTo spuBoundTo); }
SpuInfoServiceImpl:调用具体实现
@Resource private CouponFeignService couponFeignService; @Override public void savesupInfo(SpuSaveVo vo) { SpuBoundTo spuBoundTo = new SpuBoundTo(); R r = couponFeignService.saveSpuBounds(spuBoundTo); }
PS课外补充:
课堂上我没听到?自己测试得出一条经验:
接口提供方为get请求时(参数可加RequestParam也可不加),接口调用方fenservice必须要对参数进行@RequestParam注解修饰,否则会调用接口失败,在接口提供方报:Request method 'POST' not supported,在接口调用方直接出一堆错405,
关键代码:
接口提供方CouponController
@RefreshScope @RestController @RequestMapping("coupon/coupon") public class CouponController { @Autowired private CouponService couponService; @GetMapping("/test2") public R test2( @RequestParam("msg")String msg){ return R.ok().put("coupon", "hello"+msg); } }
接口调用方openfeignservice:
@FeignClient("gulimall-coupon") public interface CouponFeignService { @RequestMapping("/coupon/coupon/test2") public R test2(@RequestParam("msg") String msg); }
本文来自博客园,作者:每天都要学一点,欢迎讨论和转载,转载请注明原文链接:https://www.cnblogs.com/yanan7890/p/14983182.html