**需求:调用远程供应商接口 http:///admin/getUser 拿到我们想要的信息
一.调用方代码
@Api(tags = "调用模块")
@Slf4j
@RestController
@RequestMapping("/web")
public class UserController extends BaseController {
@Resource
private RemoteUserService remoteUserService;
@GetMapping("/getUser")
public String getUser(Long userId){
return remoteUserService.remoteGetUser(userId).checkAndGet();
}
}
二.远程feign代码
/**
* @author: wfs
* @date: 2022/3/15 18:24
* @version: 1.0
*/
@FeignClient(name = "remoteGetUserService", url = "http://localhost:***",fallbackFactory = RemoteGetUserFactory.class )
public interface RemoteGetUserService {
/**
* 获取用户信息
* @param userId 用户id
* @return 结果
*/
@GetMapping("/admin/getUser")
R<String> getLoginUser (@RequestParam("userId") Long userId);
}
1.@FeignClient标签的常用属性如下:
内容 | 含义 |
---|---|
value | 当前服务名 |
name | 指定FeignClient的名称,如果项目使用了Ribbon,name属性会作为微服务的名称,用于服务发现 |
url | url一般用于调试,可以手动指定@FeignClient调用的地址 |
decode404: | 当发生http 404错误时,如果该字段位true,会调用decoder进行解码,否则抛出FeignException |
configuration | Feign配置类,可以自定义Feign的Encoder、Decoder、LogLevel、Contract |
fallback | 定义容错的处理类,当调用远程接口失败或超时时,会调用对应接口的容错逻辑,fallback指定的类必须实现@FeignClient标记的接口 |
fallbackFactory | 工厂类,用于生成fallback类示例,通过这个属性我们可以实现每个接口通用的容错逻辑,减少重复的代码 |
path | 定义当前FeignClient的统一前缀 |
三.熔断代码
import com.guodian.api.model.client.RemoteGetUserService;
import com.guodian.common.core.domain.R;
import feign.hystrix.FallbackFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author: WuFuShan
* @date: 2022/3/16 8:38
* @version: 1.0
*/
public class RemoteGetUserFactory implements FallbackFactory<RemoteGetUserService> {
private static final Logger log = LoggerFactory.getLogger(RemoteGetUserService.class);
@Override
public RemoteGetUserService create(Throwable throwable) {
log.info("远程WebSocket服务调用失败!{}", throwable.getMessage());
return new RemoteGetUserService() {
@Override
public R<String> getLoginUser(Long userId) {
return R.fail("获取用户信息失败!!");
}
};
}
}
四.Ribbon+Hystrix熔断 依赖+配置
请看我的这片文档 包含(微服务跨模块调用) 更详细 请点击