springcloud中组件feign使用研究记录

feign请求有两种方式:
第一种,注解中直接使用spring.application.name,就是注解中name直接等于被调用的项目的name名。

@FeignClient(name="clientname")
public interface GoodsRemote 
    @RequestMapping(method = RequestMethod.POST , value = "/sso/getuser")
    public ResultResp getUserResp(@RequestBody Map<String, String> paraMap);
}

这种使用方法有一个缺陷,就是说如果两个不同网段的项目同时注册到eureka中,则不能互相调用(在eureka中注册时使用的是内网ip)。如果在eureka中注册时改为外网ip,则可能为增加dns解析的麻烦。

第二种,注解中把url带着,使用时很简单,只要@Autowired注入,就可以当作service使用了。

@FeignClient(name="clientname",url = "http://111.11.11.111:8080")
public interface GoodsRemote 
    @RequestMapping(method = RequestMethod.POST , value = "/sso/getuser")
    public ResultResp getUserResp(@RequestBody Map<String, String> paraMap);
}

这时,可以访问不同网段的被调用的项目,如果项目没被注册到eureka中,也可以访问。估计底层被解析成链接访问了。

@FeignClient(name = "${feign.name}", url = "${feign.url}")

项目信息还可以通过$取配置文件的信息。
feign还可以通过注解自定义配置,也可以通过yml文件定义,但是版本不一样,貌似好多配置不兼容。

@Configuration
//@EnableDiscoveryClient
//@EnableFeignClients(basePackageClasses = { GoodsRemote.class })
//@ComponentScan(basePackageClasses = { GoodsRemote.class })
public class FeignClientConfiguration {
    @Bean
    public Request.Options options() {
        return new Request.Options(
                6000,
                6000
        );
    }    
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
}

这里配置了请求超时时间和日志级别,日志又四种级别:
NONE, No logging (DEFAULT).

BASIC, Log only the request method and URL and the response status code and execution time.

HEADERS, Log the basic information along with request and response headers.

FULL, Log the headers, body, and metadata for both requests and responses.

feign还可以进行熔断,就是说当查询超时,并且重试失败,则会调用熔断的方法。

@FeignClient(name = "hello", fallback = HystrixClientFallback.class)
protected interface HystrixClient {
    @RequestMapping(method = RequestMethod.GET, value = "/hello")
    Hello iFailSometimes();
}

static class HystrixClientFallback implements HystrixClient {
    @Override
    public Hello iFailSometimes() {
        return new Hello("fallback");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值