`
lobin
  • 浏览: 378980 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论
阅读更多

Ribbon是微服务的一个核心基础组件,提供多协议HTTP、TCP以及UDP的服务调用RPC功能以及负载均衡功能。

Ribbon:一个客户端IPC(Inter Process Communication)库,RPC(Remote Procedure Calls)库。支持负载均衡、故障容错、多协议支持:HTTP, TCP, UDP,支持异步(asynchronous)以及reactive模型、Caching 以及batching。

 

Ribbon 注解方式

 

举例某个api应用,运行了两个实例(部署了2台机器),这个应用提供了两个api:

1、/test

2、/test/{version}

这两个api都有个参数data,/test/{version}还有个@PathVariable的version参数。

/test定义如下:

@ResponseBody
@RequestMapping(value = "test")
public String test(@RequestParam String data) {
    return data;
}

/test/{version}定义如下:

@ResponseBody
@RequestMapping(value = "test/{version}")
public String testvn(@PathVariable String version, @RequestParam String data) {
    return data + ";version=" + version;
}

就是两个普通的api,和我们以前写的api是一样的,可以直接请求:

http://localhost:8081/test?data=aaa

http://localhost:8082/test?data=aaa

 

http://localhost:8081/test/1.0?data=aaa

http://localhost:8082/test/1.0?data=aaa

 

通过ribbon调用这俩个api服务:

 

注解方式:

public interface TestService {

    @Http(
            method = Http.HttpMethod.GET,
            uri = "/test?data={data}"
    )
    RibbonRequest<ByteBuf> test(@Var("data") String data);

    @Http(
            method = Http.HttpMethod.GET,
            uri = "/test/{version}?data={data}"
    )
    RibbonRequest<ByteBuf> testvn(@Var("version") String version, @Var("data") String data);
}

通过ribbon调用/test服务:

@Test
public void test11() {
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");

    TestService testService = Ribbon.from(TestService.class);
    RibbonRequest<ByteBuf> request = testService.test("aaa");

    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

通过ribbon调用/test/{version}服务:

@Test
public void test21() {
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");

    TestService testService = Ribbon.from(TestService.class);
    RibbonRequest<ByteBuf> request = testService.testvn("1.0", "aaa");

    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

 

 

 

Case: Instant messaging communication  over XMPP base TCP

 

----------------------------------------------------------------

 

Little thinking of interpreting XML document using automata

 

Little thinking of interpreting XML document using automata

 

- Attachment are just to attempt to interpret a simple document element like:

 

<e from='je@localhost.com' to='localhost.com' version='1.0' xml:lang='en' xmlns='jx:clc' xmlns:e='http://ex.jx.org/e'>

 

the element is not a completed XML document element util.

 

 


-----------------------------------------------------------------------

Ribbon:一个客户端IPC(Inter Process Communication)库,RPC(Remote Procedure Calls)库。支持负载均衡、故障容错、多协议支持:HTTP, TCP, UDP,支持异步(asynchronous)以及reactive模型、Caching 以及batching。

 

Ribbon和Eureka配合用于发现查找注册的服务。Ribbon根据查找到的服务列表负责将请求路由转发到后端的服务(负载均衡)。

 

Eureka是一个微服务注册中心(registry),服务通过将自己注册在registry以便于服务进行发现定位查找。

 


HTTP请求,Template方式:
http://localhost:8081/test?data=aaa

@Test
public void test1() {
    HttpResourceGroup httpResourceGroup = Ribbon.createHttpResourceGroup("movieServiceClient",
            ClientOptions.create()
                    .withMaxAutoRetriesNextServer(3)
                    .withConfigurationBasedServerList("localhost:8082,localhost:8081"));
    HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class)
            .withMethod("GET")
            .withUriTemplate("/test?data=aaa")
//                .withFallbackProvider(new RecommendationServiceFallbackHandler())
//                .withResponseValidator(new RecommendationServiceResponseValidator())
            .build();
    RibbonRequest<ByteBuf> request = recommendationsByUserIdTemplate.requestBuilder()
            .build();


    // Observable<ByteBuf> result = request.observe();


    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

 http://localhost:8082/test/1.0?data=aaa

@Test
public void test2() {
    HttpResourceGroup httpResourceGroup = Ribbon.createHttpResourceGroup("movieServiceClient",
            ClientOptions.create()
                    .withMaxAutoRetriesNextServer(3)
                    .withConfigurationBasedServerList("localhost:8082,localhost:8081"));
    HttpRequestTemplate<ByteBuf> recommendationsByUserIdTemplate = httpResourceGroup.newTemplateBuilder("recommendationsByUserId", ByteBuf.class)
            .withMethod("GET")
            .withUriTemplate("/test/{version}?data=aaa")
//                .withFallbackProvider(new RecommendationServiceFallbackHandler())
//                .withResponseValidator(new RecommendationServiceResponseValidator())
            .build();
    RibbonRequest<ByteBuf> request = recommendationsByUserIdTemplate.requestBuilder()
            .withRequestProperty("version", "1.0")
            .build();


    // Observable<ByteBuf> result = request.observe();


    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

 注解方式:

public interface TestService {

    @Http(
            method = Http.HttpMethod.GET,
            uri = "/test?data={data}"
    )
    RibbonRequest<ByteBuf> test(@Var("data") String data);

    @Http(
            method = Http.HttpMethod.GET,
            uri = "/test/{version}?data={data}"
    )
    RibbonRequest<ByteBuf> testvn(@Var("version") String version, @Var("data") String data);
}

 

@Test
public void test11() {
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");

    TestService testService = Ribbon.from(TestService.class);
    RibbonRequest<ByteBuf> request = testService.test("aaa");

    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

 

@Test
public void test21() {
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.MaxAutoRetriesNextServer, "3");
    ConfigurationManager.getConfigInstance().setProperty("TestService.ribbon." + CommonClientConfigKey.ListOfServers, "localhost:8082,localhost:8081");

    TestService testService = Ribbon.from(TestService.class);
    RibbonRequest<ByteBuf> request = testService.testvn("1.0", "aaa");

    ByteBuf result0 = request.execute();
    ByteBuffer buf = result0.nioBuffer();
    byte[] bytes = new byte[buf.remaining()];
    buf.get(bytes);
    System.out.println(new String(bytes));
}

负载均衡

class URLConnectionLoadBalancer {

    private final ILoadBalancer loadBalancer;
    // retry handler that does not retry on same server, but on a different server
    private final RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(0, 1, true);

    public URLConnectionLoadBalancer(List<Server> serverList) {
        loadBalancer = LoadBalancerBuilder.newBuilder().buildFixedServerListLoadBalancer(serverList);
    }

    public String call(final String path) throws Exception {
        return LoadBalancerCommand.<String>builder()
                .withLoadBalancer(loadBalancer)
                .build()
                .submit(new ServerOperation<String>() {
                    @Override
                    public Observable<String> call(Server server) {
                        URL url;
                        try {
                            url = new URL("http://" + server.getHost() + ":" + server.getPort() + path);
                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            
                            InputStream is = conn.getInputStream();
                            ByteArrayOutputStream os = new ByteArrayOutputStream();
                            byte[] bytes = new byte[1024];
                            int nbytes = -1;
                            while ((nbytes = is.read(bytes)) > 0) {
                                os.write(bytes, 0, nbytes);
                            }
                            String content = new String(bytes);
                            content = content.trim();
                            
//                            content = conn.getResponseMessage();
                            
                            return Observable.just(content);
                        } catch (Exception e) {
                            return Observable.error(e);
                        }
                    }
                }).toBlocking().first();
    }

    public LoadBalancerStats getLoadBalancerStats() {
        return ((BaseLoadBalancer) loadBalancer).getLoadBalancerStats();
    }
}

 

@Test
public void test() {
    URLConnectionLoadBalancer urlLoadBalancer = new URLConnectionLoadBalancer(Lists.newArrayList(
            new Server("localhost", 8081),
            new Server("localhost", 8082)));
    for (int i = 0; i < 6; i++) {
        try {
            System.out.println(urlLoadBalancer.call("/test?data=aaa"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    System.out.println("=== Load balancer stats ===");
    System.out.println(urlLoadBalancer.getLoadBalancerStats());
}

 

1、https://github.com/Netflix/eureka

 

 

Ribbon还提供了一个template方式来请求HTTP资源,Template方式可参考文章: https://lobin.iteye.com/blog/1576159

Ribbon负载均衡例子参考文章: https://lobin.iteye.com/blog/1576159

 

 

 

1、https://github.com/Netflix/ribbon

0
0
分享到:
评论

相关推荐

    微服务微服务微服务微服务.zip

    微服务

    (完整版)基于SpringCloud微服务系统设计方案.pdf

    (完整版)基于SpringCloud微服务系统设计方案.pdf(完整版)基于SpringCloud微服务系统设计方案.pdf(完整版)基于SpringCloud微服务系统设计方案.pdf(完整版)基于SpringCloud微服务系统设计方案.pdf(完整版)基于Spring...

    微服务请求日志统一处理方案

    问题:在微服务中如何对请求日志统一输出? 新建日志组件,日志组件对请求进行拦截处理,输出请求入参、出参。其他各微服务引用日志组件,对日志统一输出 日志组件如下: 工具类 1、新建TimeCostEnum 请求耗时类,...

    基于SpringCloud微服务架构社交系统的设计与实现

    ②数据爬取、数据智能分类、消息通知微服务、即时通讯微服务、问答微服务、活动微服务、吐槽微服务、招聘微服务、头条微服务、交友微服务都是如何设计和实现的。 阅读建议:此资源以开发SpringCloud微服务架构社交...

    (完整版)基于SpringCloud微服务系统设计方案.docx

    (完整版)基于SpringCloud微服务系统设计方案.docx(完整版)基于SpringCloud微服务系统设计方案.docx(完整版)基于SpringCloud微服务系统设计方案.docx(完整版)基于SpringCloud微服务系统设计方案.docx(完整版)基于...

    SpringCloud微服务接口这么多怎么调试

    本文来自程序猿,本文主要介绍了SpringCloud微服务下服务接口调试及管理,什么样方式可以让微服务的接口管理变得更加容易些,希望对您的学习有所帮助。我们知道在微服务架构下,软件系统会被拆分成很多个独立运行的...

    基于SpringCloud-微服务系统设计方案.docx

    微服务架构从本质上说其实就是分布式架构,与其说是一种新架构,不如说是一种微服务架构风格。 简单来说,微服务架构风格是要开发一种由多个小服务组成的应用。每个服务运行于独立的进程,并且采用轻量级交互。多数...

    架构探险轻量级微服务架构(下册)

    资源名称:架构探险 轻量级微服务架构(下册)内容简介:《架构探险:轻量级微服务架构(下册)》将重点关注微服务基础设施方面,其中大部分内容涉及微服务运维相关技术。《架构探险:轻量级微服务架构(下册)》以...

    基于微服务的网上商城系统的设计与实现

    内容概要:通过带着读者使用微服务的架构进行设计,保证业务之间充分解耦, 服务之间独立运行,实现拓展性高、高可用与高并发的商城系统。系 统功能的单体结构以微服务的形式存在(包括购物车管理服务、中央 认证...

    微服务学习资料 帮我们入门微服务的相关知识

    在介绍微服务时,首先得先理解什么是微服务,顾名思义,微服务得从两个方面去理解,什么是"微"、什么是"服务", 微 狭义来讲就是体积小、著名的"2 pizza 团队"很好的诠释了这一解释(2 pizza 团队最早是亚马逊 CEO ...

    面试中的微服务.pdf

    面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf面试中的微服务.pdf...

    SpringCloud微服务笔记

    ## 微服务概述 [马丁福勒微服务论文]: https://martinfowler.com/articles/microservices.html ### 什么是微服务 - 目前的微服务并没有一个统一的标准,一般是以业务来划分 - 将传统的一站式应用,拆分成一个个...

    2019年SpringCloud 微服务实战之气象预报平台实战

    2019年SpringCloud 微服务实战之气象预报平台实战 包含11章节+项目源码 目录: 第9章 微服务的集中化配置 第8章 API 网关 第7章 微服务的消费 第6章 微服务的注册与发现 第5章 微服务的协调者Spring ...

    微服务架构.ppt

    微服务架构.ppt 是关于微服务架构学习的一款非常好的ppt。

    java毕业设计—基于微服务的医院挂号系统.zip

    java毕业设计—基于微服务的医院挂号系统。已获通过的高分项目。使用微服务,redis,rabbitmq,springcloud搭建的一个微服务项目。java毕业设计—基于微服务的医院挂号系统。已获通过的高分项目。使用微服务,redis,...

    微服务架构设计.doc

    微服务架构设计

    微服务介绍/微服务架构方案PPT

    微服务介绍/微服务架构方案PPT,新手学习参考资料!

    基于微服务和Docker容器技术的PaaS云平台架构设计.docx

    基于微服务架构和Docker容器技术的PaaS云平台建设目标是给我们的开发人员提供一套服务快速开发、部署、运维管理、持续开发持续集成的流程。平台提供基础设施、中间件、数据服务、云服务器等资源,开发人员只需要开发...

    微服务网关入门.zip

    微服务网关的基本功能和多种网关对比,spring cloud gateway的基本使用。 服务网关是微服务架构中的一个关键的角色,用来保护、增强和控制对于微服务的访问,服务网关是一个处于应用程序或服务之前的系统,用来管理...

    黄勇-微服务.pdf

    黄勇-微服务.pdf 自从 Martin Fowler(福勒)提出了 Micro Service(微服务)的概念后,业界就卷起了 一股关于微服务的热潮,大家谈论多年的 SOA(Service-Oriented Architecture,面向服 务的架构)终于有了新的...

Global site tag (gtag.js) - Google Analytics