首页 > 技术文章 > Feign使用注意事项

lyalong 2020-12-09 16:47 原文

使用Feign时,为了不写重复代码,需要写feign公共接口方便调用,这时候需要注意以下问题,以发邮件为例

定义公共接口

/**
 * @author liuyalong
 * @date 2020/10/12 17:42
 * 定义Feign公用接口,注意 [不能] 在类上写@RequestMapping("/email")注解,不然会报Ambiguous mapping错误
 */
//@RequestMapping("/email")   不能在这里写!!!
public interface BaseMailController {
    /**
     * 在为Feign定义服务标准接口的时候,处理请求参数的方法参数,必须使用@RequestParam注解描述。
     * 并且,无论方法参数名和请求参数名是否一致,都需要定义@RequestParam注解的value/name属性。
     * 在Feign技术中,默认的发起POST请求的时候,请求的参数,都是在请求体中使用JSON数据传递的,不是name=value对传递的。
     * 默认环境中,只要是Feign发起的POST请求,请求参数都是JSON数据。必须使用@RequestBody处理。
     */
    @PostMapping("/email/sendEmail")
    BaseCommonResult<Integer> sendEmail(
            @RequestParam(value = "to") String[] to,
            @RequestParam(value = "subject") String subject,
            @RequestParam(value = "text") String text,
            @RequestParam(value = "filenames", required = false) String[] filenames

    );

}

Feign调用

@RestController
public class SendEmailController implements BaseMailController {

    @Autowired
    private MailServices mailServices;

    /**
     *
     在接口中,已经将请求URL和方法耦合到一起了。
     * 所以在当前的控制器中,不能重复定义@RequestMapping来约束请求URL,
     * 不需要再使用@PathVariable,但是POST请求的JSON数据还是要使用@RequestBody
     */
    @Override
    public BaseCommonResult<Integer> sendEmail(
            @RequestParam(value = "to") String[] to,
            @RequestParam(value = "subject") String subject,
            @RequestParam(value = "text") String text,
            @RequestParam(value = "filenames", required = false) String[] filenames

    ) {
        EmailEntity emailEntity = new EmailEntity();
        emailEntity.setFilenames(filenames);
        emailEntity.setSubject(subject);
        emailEntity.setText(text);
        emailEntity.setTo(to);

        try {
            mailServices.sendMail(emailEntity);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseCommonResult.failed("邮件发送失败");
        }

        return BaseCommonResult.success(1, "邮件发送成功");
    }

}

推荐阅读