在穀粒商城學習——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); }