springcloud中的feign使用

我们使用springcloud的feign,可以让我们像调用本地方法似的调用远程方法,就和dubbo类似。但是,使用feign的时候,

我们要注意几点。

首先,我们要开启feign。

@EnableFeignClients

该注解就可以开启feign功能。


使用feign的时候,参数上我们一定要加@RequestParam,@RequestBody等注解,不然的话就会报错。

使用方法:

@FeignClient(name = "projectName", path = "projectName")
public interface Facade{
    @RequestMapping(value="/test",method=RequestMethod.GET)
    @ResponseBody
    String test(@RequestParam("testParam")String testParam);

@FeignClient里面指定要调用的工程的工程名,就是springboot的配置文件中配置的应用名

spring.application.name=projectName

它会根据应用名在服务注册中心查找到该应用的访问地址。


@RequestMapping()  指定的是访问方法的路径

@RequestParam()     这里要注意,如果使用feign,一定要在参数上加上这样的注解,不然会出错。


定义好接口后,只要在projectName的应用中,引入该接口jar包,实现该接口,就可以了,不过要在参数上加注解,不必在实现类中加其他注解了。

然后调用方,引入该接口jar包,然后使用该接口直接像本地方法调用就可以直接调用projectName中的方法实现了。


还有一点,因为feign调用出错后,返回的信息乱七八糟的,包含很多html格式,所以我们可以定义一个切面,在feign出错的时候,通过该切面

解析一下返回的出错信息就可以了。

@Component
@Aspect
public class ExceptionAdvice {
    private static final String prefix = "content:\n{";
    private static final int prefixLength = prefix.length();
    private static final String suffix = "}";
    private static final JsonParser jsonParser = new JacksonJsonParser();

    @AfterThrowing(value = "execution(
            "!execution(* (@org.springframework.web.bind.annotation.RestController *).*(..))" +
            "&& !execution(* (@org.springframework.stereotype.Controller *).*(..))", throwing="e")
    public Object afterThrowing(Throwable e) throws Throwable {
        if (e instanceof FeignException) {
            String m = e.getMessage();
            if (m.indexOf(prefix) != -1) {
                String s = m.substring(m.indexOf(prefix) + prefixLength - 1, m.indexOf(suffix) + 1);
                Map<String, Object> resMap = jsonParser.parseMap(s);
                String exceptionName = (String) resMap.get("exception");
                String message = (String) resMap.get("message");
                Class<Throwable> throwableClass;
                try {
                    throwableClass = (Class<Throwable>) Class.forName(exceptionName);
                } catch (ClassNotFoundException e1) {
                    throw new Exception(message);
                }

                Constructor<Throwable> constructor = throwableClass.getConstructor(String.class);
                Throwable throwable = constructor.newInstance(resMap.get("message"));
                throw throwable;
            }
        }

        throw e;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值