SpringCloud Feign用法

发布于:2024-06-01 ⋅ 阅读:(127) ⋅ 点赞:(0)

1.在目标应用的启动类上添加开启远程fein调用注解:

2.添加一个feign调用的interface

@FeignClient("gulimall-coupon")
public interface CouponFeignService {

    @PostMapping("/coupon/spubounds/save")
     R save(@RequestBody SpuBondTo spuBounds);
}

 接口上添加注解@FeignClient,括号内填入要远程调用的微服务应用名application name; 

3.添加要调用远程服务controller里对应的方法声明,注意是方法声明,没有方法体,这一步需确保:

1.http请求方法要一致,源方法用get请求,调用处也要用get请求;

2.http请求方法路径要完整,@GetMapping和@PostMapping里的路径地址

3.传参方式要一致,比如@RequestBody,@RequestParam,@PathVariable; 

4.返回值要一致;

需要特别指出的是像@RequestBody传参,源方法和feignClient调用处可用不同的对象,只要保证这2个对象有业务需要的部分相同属性即可。

下面贴上代码方便理解

Controller里的方法:

@RestController
@RequestMapping("coupon/spubounds")
public class SpuBoundsController {
    
    @Autowired
    private SpuBoundsService spuBoundsService;
    
    @PostMapping("/save")
    public R save(@RequestBody SpuBoundsEntity spuBounds){
		spuBoundsService.save(spuBounds);
        return R.ok();
    }

SpuBondTo 实体类(前端传参对象)

@Data
public class SpuBondTo {

    private Long spuId;
    private BigDecimal buyBounds;
    private BigDecimal growBounds;
}

controller里的传参,对应数据库表的实体类

@Data
@TableName("sms_spu_bounds")
public class SpuBoundsEntity implements Serializable {

	private static final long serialVersionUID = 1L;

	/**
	 * id
	 */
	@TableId
	private Long id;
	/**
	 * 
	 */
	private Long spuId;
	/**
	 * 成长积分
	 */
	private BigDecimal growBounds;
	/**
	 * 购物积分
	 */
	private BigDecimal buyBounds;
	/**
	 * 优惠生效情况
     */
	private Integer work;

}

这2个对象中有3个属性是一致的,如此部分属性相同即可实现Feign远程调用伟参,当然传同一类型的实体更不用说了。


网站公告

今日签到

点亮在社区的每一天
去签到