版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30698633/article/details/77251647
我们使用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;
}
}