首页  

feign ribbon 独立使用例子     所属分类 springcloud 浏览量 241
ribbon  客户端负载均衡

Feign  轻量级 RESTful 客户端
Feign makes writing java http clients easier
内置Ribbon 实现 客户端负载均衡
使用Feign的注解定义接口

OpenFeign 在Feign的基础上支持SpringMVC注解,如@RequesMapping等

@FeignClient可以解析SpringMVC的@RequestMapping 等注解
通过动态代理的方式产生实现类

feign ribbon  可以脱离 spring 独立使用


客户端负载均衡 ILoadBalancer balancer = new BaseLoadBalancer(); List servers = new ArrayList(); servers.add(new Server("localhost", 8080)); servers.add(new Server("localhost", 8081)); balancer.addServers(servers); for(int i=0;i<10;i++){ Server choosedServer = balancer.chooseServer(null); System.out.println(choosedServer); } 服务列表可以在 注册中心 动态维护
private static interface InfoService{ @RequestLine("GET /info") String info(); } Properties properties = new Properties(); properties.put("demo.ribbon.MaxAutoRetries","1"); properties.put("demo.ribbon.OkToRetryOnAllOperations","true"); properties.put("demo.ribbon.ServerListRefreshInterval","2000"); properties.put("demo.ribbon.ConnectTimeout","2000"); properties.put("demo.ribbon.ReadTimeout","3000"); properties.put("demo.ribbon.listOfServers","localhost:8080,localhost:8090"); properties.put("demo.ribbon.EnablePrimeConnections","true"); // prefix demo ==> appName // http://demo ConfigurationManager.loadProperties(properties); InfoService infoService = Feign.builder().client(RibbonClient.create()) //.encoder(new JacksonEncoder()) //.decoder(new JacksonDecoder()) .target(InfoService.class,"http://demo"); for(int i=0;i<10;i++) { System.out.println(infoService.info()); }
服务端 https://gitee.com/dyyx/springboothello mvn spring-boot:run -Dstart-class=demo.DemoApp -Dspring-boot.run.arguments=--server.port=8080 mvn spring-boot:run -Dstart-class=demo.DemoApp -Dspring-boot.run.arguments=--server.port=8090
pom依赖 com.netflix.ribbon:ribbon-loadbalancer:2.2.5 com.netflix.ribbon:ribbon-httpclient:2.2.5 com.netflix.archaius:archaius-core:0.7.6 io.github.openfeign:feign-core:9.5.1 io.github.openfeign:feign-ribbon:9.5.1 io.github.openfeign:feign-jackson:9.5.1 io.github.openfeign:feign-jackson:9.5.1
完整代码 https://gitee.com/dyyx/demos/tree/master/feign-riboon-demo

上一篇     下一篇
Hystrix实例

SpringMVC @ControllerAdvice 注解

springboot读取配置的几种方式

springcloud zuul 简介

SpringBoot注册Servlet的三种方式

springboot获取内置tomcat端口