Go-kit 入门(四)服务调用

调用服务

存在“真空”(即极其独立,与其他任何服务无互相调用的关系)中的服务是罕见的。而我们常见的是,我们需要调用其他的服务。这也是 Go kit 的闪光点 ,我们提供了 传输中间件 机制来解决可能出现的很多问题。

下面我们将实现一个代理功能的中间件,作为一个服务中间件。在这里我们只代理一个方法,Uppercase。

客户端端点

我们已经有了一个跟我们所知道的完全相同的端点,但是我们将使用它来调用一个请求,而不是提供服务。按照这种方式来使用它的时候,我们称它为客户端端点。为了调用客户端端点,我们需要做一些简单的转换。

现在,我们为了构造一个代理中间件,我们将一个代理URL字符串转换为一个端点。加入我们使用 HTTP 协议之上的 JSON,我们可以使用 transport/http 包中的一个辅助(helper)函数。

服务发现和负载均衡

如果我们只使用一个远程的服务就好了。但是实际上,我们往往 会有很多个服务实例。我们希望通过一些服务发现算法来发现它们,然后将我们的负载分散到它们上面,并且如果这些实例中的任何一个变得糟糕,我们能够处理它,并且不影响我们服务的可用性。

Go kit 为不同的服务发现系统提供了适配器,为了获取最新的服务实例集合,暴露端点个体。这些适配器被称为 发布器(publishers)。

在发布器内部,它使用一个私有的工厂函数,将被发现的每一个 host:port 字符串 转换成一个可用的端点。

目前,我们的工程方法,makeUppercaseEndpoint,只是直接请求 URL。但是,在工厂函数中加入一些安全的中间件方法是很重要的,比如 回路断路器 和 限流器。

现在,我们已经有了一系列的端点,我们需要在其中选择一个。负载均衡器包装了 发布器,并且从端点集合中选择其中的某一个。Go kit 提供了一组基本的负载均衡器,并且,如果你希望更多的高级的算法,也可以很容易的自己来写一个。

现在,我们可以根据一下算法来选择端点。我们能够使用它为消费器提供一个单一的、逻辑的可靠的端点。通过重试的策略包装负载均衡器,并且返回一个可用的端点。重试的策略可以将一个失败的请求进行重试,直到达到最大的可重试次数或是达到超时时间。

现在,让我们将最后的代理中间件加入到代码中。为了简洁,我们假设用户会为逗号(,)分隔的多个实例端点指定一个标记。

stringsvc3

截止目前,这个完整的服务是 stringsvc3$ go get github.com/go-kit/kit/examples/stringsvc3 $ stringsvc3 -listen=:8001 & listen=:8001 caller=proxying.go:25 proxy_to=none listen=:8001 caller=main.go:72 msg=HTTP addr=:8001 $ stringsvc3 -listen=:8002 & listen=:8002 caller=proxying.go:25 proxy_to=none listen=:8002 caller=main.go:72 msg=HTTP addr=:8002 $ stringsvc3 -listen=:8003 & listen=:8003 caller=proxying.go:25 proxy_to=none listen=:8003 caller=main.go:72 msg=HTTP addr=:8003 $ stringsvc3 -listen=:8080 -proxy=localhost:8001,localhost:8002,localhost:8003 listen=:8080 caller=proxying.go:29 proxy_to="[localhost:8001 localhost:8002 localhost:8003]" listen=:8080 caller=main.go:72 msg=HTTP addr=:8080

高级话题

线程上下文

上下文对象用来在单个请求中携带那些需要跨越概念性边界的信息。在我们的例子中,我们还没有在业务逻辑中使用线程上下文。但是,这种方式几乎会永远都是一个好方案。它允许我们在业务逻辑和中间件中传递请求范围内的信息,并且对于复杂的任务(比如,分布式系统的细粒度追踪信息)也是很必要的。

具体点来讲,这也意味着你的业务逻辑接口会这样:

 

请求跟踪

一旦你的基础设施增长超过一定的规模,在多个服务中跟踪请求是非常必要的,这样,你就能够分析并解决故障热点。参见 package tracing 获取更多信息。

创建一个客户端软件包

使用 Go kit 为你的服务创建一个客户端软件包是很可能的事情,让你的服务能够很容易对其他的 Go 程序进行调用。实际上,你的客户端package会提供你的服务接口,这个接口会使用指定的传输方式来调用远程服务。参见 package addsvc/client 作为参考例子.

其他例子

addsvc

addsvc 是原来的一个例子。它公开 所有支持的传输方式 的系列操作。它完整地做了日志记录、仪表盘化,并且使用 Zipkin 来跟踪请求。同样,它也示范了如何创建和使用客户端package。它是一个非常棒的例子,为 Go kit 服务提供了完整的功能示例。

profilesvc

profilesvc 示范了如何使用 Go kit 来打造 REST 风格的微服务。

apigateway

apigateway 示范了如何实现一个 API 网关模式,通过 Consul 作为服务发现系统。

shipping

shipping 是一个完整的,真实的应用,由多个微服务组成,基于领域驱动设计原则。

|2|left
此条目发表在MircroService分类目录,贴了, 标签。将固定链接加入收藏夹。

Go-kit 入门(四)服务调用》有 594 条评论

  1. agoriarat说:

    évidemment, les plus grands vont charger un Nike Air Max 1 Femme Noir peu plus et les types les plus compacts vont un peu moins. Le couteau USA KA-BAR Fighting / Utility est devenu l’un des couteaux les plus populaires. Nike Shox Monster SI couvrant comme réalisable.Il ya quelques simulations de chaussures Geox qui ne sont pas pensés pour se porter dans un Officiel Fran?ais Adidas Superstar environnement Nike Shox Monster SIt. Ceux-ci causeront de l’arthrite à une blessure. Ceux qui recueillent des chaussures Nike Air Force A ont été gatés pour le choix sur ce front. Nike a même fabriqué de nouveaux modèles de baskets spécialement con?us pour les vidéos de hip-hop qui Nike Air Max Zero Femme ont été une sorte de placement de solution.
    xlccl20180412er

  2. Mauntob说:

    Химический спектральный анализ – http://www.khimex.ru/

  3. Save Money & Grow Your Business QuickBooks Enterprise- Free Trial Adobe Dreamweaver

    cheapest solidworks software
    adobe photoshop cs6 student version
    buy adobe master collection cs5
    best price adobe acrobat x standard
    adobe creative suite 6 production premium download
    military discount windows 7
    buy solidworks for home use
    price adobe acrobat
    autocad 2016 price list
    windows 7 family pack upgrade clean install
    purchase autocad civil 3d 2015

  4. Improve Efficiency of Budgeting & Forecasting. Download a Free Trial Adobe Photoshop

    adobe creative suite 5.5 design premium mac
    adobe acrobat xi standard vs pro
    buy adobe photoshop elements for mac
    adobe photoshop software online
    purchase autocad lt
    buy adobe acrobat x standard download
    windows 7 upgrade license 32 bit to 64 bit
    microsoft excel and word
    adobe photoshop elements 15
    buy revit 2016
    where can i buy photoshop elements 11

  5. agoriarat说:

    For example, if you purchase a chunk of land, and later on build it incorporates cheap basketball jerseys china risky products beneath the area, you’ll like a law firm to sue the seller making sure that they are accountable for the cleanup rates. The Judges dress in blinders much like the horses in the race monitor. People that have passion for these things use a great deal creativeness to achieve wonderful works of arts. So maybe this trend of dressing up our dogs in sports attire and jazzing them up with accompanying accessories might be exciting. I assumed who could not catch a ball from the bat of the twelve 12 months old or at the least deflect it absent. Other particular personal injury wholesale nba jerseys businesses (typically massive firms), can cowl all fees and expenditures.
    xlddl20180412er

  6. Ldip说:

    http://krimexpert.ru/ – почерковедческая экспертиза подписи умершего человека

  7. Find Free Budget Planners Online. Create Your Own Budget Plan Today! buy now!

    adobe online store uk
    purchase autodesk revit 2015
    adobe cs6 design standard download
    windows 7 32 bit uk
    cheap autocad lt 2012
    adobe indesign cs6 mac trial
    adobe master collection cs6 price amazon
    buy adobe acrobat professional india
    price solidworks
    discount photoshop for students
    windows 7 price indian rupees

  8. TeN说:

    Лингвистический анализ текстов – http://lingex.ru/

  9. UpTo 40% Off Cheap Window Huge Cyber Monday Deals Now! Adobe Premiere Elements

    buy autodesk sketchbook
    price adobe photoshop cs6 for mac
    microsoft excel and word not responding
    buy photoshop cs6 mac
    adobe master collection cs6 student price
    adobe creative suite cs6 mac download
    price solidworks 2017
    photoshop cs6 where are actions stored
    purchase revit 2014
    cost of autocad lt 2016
    buy microsoft office pro 2007

  10. agoriarat说:

    Le nouveau Kelty Child Carriers fournit également le même cockpit structuré Nike Internationalist Femme V-Bar, également connu sous le nom de cage de sécurité. Il s’agit généralement d’un appareil minuscule, beaucoup plus petit que votre téléphone portable, et il se branche idéalement sur la prise audio de votre téléphone cellulaire ou de votre lecteur MP3. Le type d’escargot est un escargot terrestre commun brun qui partage en réalité des similitudes dramatiques dans les caractéristiques de la peau avec les humains. La sécrétion est recueillie dans une méthode s?re et transformée en une crème inodore et incolore sans ingrédients ajoutés. Faire cet exercice est un soulagement fantastique pour le pied et la réduction de l’arthrite. Il est vraiment clair quand vous finissez par lire ceci que vous désirez ajouter plus de valeur à la santé globale et à la santé Nike Air Max 98 dans votre vie quotidienne, alors appliquez ce que je vais discuter.
    xlccl20180412er

  11. Wholesale PCs starting each Free Shipping + 90 Day Warranties Adobe Premiere

    windows 7 ultimate 32 bit iso
    microsoft windows xp home edition
    adobe lightroom 6 upgrade dvd
    price of windows 7 ultimate 64 bit in india
    buy adobe creative suite outright
    best price microsoft office professional plus 2013
    best price adobe acrobat xi pro
    best buy microsoft office for macbook air
    price windows xp home edition
    best price microsoft office 2007
    purchase microsoft office student online

  12. agoriarat说:

    So, what happens whenever they do defy the pretty much unachievable odds? Winning cheap nba jerseys china the lottery might give them some cash, but it doesn’t adjust their mind set. In honor of this specific anniversary, the brand new York Rangers are unveiling Heritage 7 days, a weeklong schedule of things to do and programming from November 12-17 which will provide lovers with many opportunities to help rejoice the team fantastic heritage. England played their very first, and incidentally the world?s first ever international, in opposition to Scotland in 1871 ? and lost. All those who definitely have great deficiency often take a look at their wonderful deficiency. Today it?s common to see a Poodle rocking Mets colors on a dog baseball jersey, or his favorite football staff?s Minnesota Vikings Jersey logo on a dog football jersey. And do not just acquire their term for it.
    xlddl20180412er

  13. Frody说:

    Бюро судебно медицинской экспертизы адрес – http://www.medeksp.ru/

  14. California – Los Angeles/Orange Cty Robust ERP Ideal for small business discount software buy now!

    buy solidworks uk
    windows 7 home premium nzb
    buy adobe premiere pro without subscription
    teacher discount microsoft office for mac
    adobe dreamweaver cs6 buy online
    adobe premiere pro for mac price
    store windows 7 professional
    adobe indesign cs6 price south africa
    buy autocad 2013 full version
    purchase photoshop elements 11
    cheap adobe software for students

  15. Ahaa, its pleasant conversation concerning this paragraph at this place at this
    webpage, I have read all that, so at this time me also
    commenting at this place.

  16. agoriarat说:

    She asked Boscov’s if arrive January they would operate with her Utah Jazz school and function program. One particular with the objects of actuality reveals is sensationalizing a seemingly trivial party. As an example, in case you?re faced having a private damage scenario from a worker or shopper, an attorney will facilitate mitigate any damages. The usage of these sorts of parts can make the sneakers cozy and very effortless to walk with. This is why, he is generally out there to answer for their concerns and show up at for their teaching demands which has produced him the world’s renowned excess fat loss professional. If you love soccer and every thing about it, football shirts cheap nfl jerseys wholesale are absolutely a issue deserving of building a collection close to.
    xlddl20180412er

  17. Thank you so much! It is definitely an outstanding internet site.

    EXPERTUTLATANDE
    Manga gentleman lider av otillracklig penisstorlek. Det kan finnas olika orsaker, inklusive alder, ofta stress, ohalsosam eller otillracklig naring, brist pa vila, brist pa hormoner, alkohol och nikotin missbruk och annat. Alla leder plow samma resultat: nedgang i kvaliteten pa sexlivet.
    Under de senaste 20 aren har binge sett fellow i alla aldrar och livsstilar med detta problem. Vi lyckades hitta det perfekta botemedlet looking for att hjalpa dem. Namligen Titan Gel! Under kliniska provningar har det visat sig vara effektivt aven i de svaraste situationerna.
    Jag kan verkligen rekommendera Titan Gel site http://puela3.allformen.se/titan-gel-in-jeddah/largest-penile-length-recorded.php largest penile length recorded work alla mina patienter som den basta losningen. De som redan har provat det uppskattar det mycket!

  18. And More With Sage 300 ERP. Save Time & Money, Grow Your Business! Adobe Flash

    buy adobe acrobat professional 10
    indesign cs6 studentenversion
    microsoft office for mac download military discount
    purchase windows 7 ultimate 64 bit
    price of original windows 7 in india
    microsoft office educational discount teachers uk
    price of windows 7 ultimate in usa
    new windows 7 laptop uk
    photoshop cs6 best price australia
    windows xp 32 bit iso image download
    price windows 7

  19. I have been surfing online more than 2 hours today, yet I
    never found any interesting article like yours. It’s
    pretty worth enough for me. In my view, if all webmasters and bloggers
    made good content as you did, the web will be a lot more useful
    than ever before.

  20. Hi there! This article couldn’t be written any better!
    Looking at this article reminds me of my previous roommate!

    He constantly kept talking about this. I will forward this post
    to him. Fairly certain he will have a very good read.
    Thanks for sharing!

  21. Get Info On Cheap Software Access 10 Search Engines At Once. visit site =>

    best buy microsoft office home and student 2016
    autodesk military discount
    buy windows 7 professional 32 bit uk
    adobe master collection cs5 price in malaysia
    solidworks 2015 price australia
    cheap+adobe acrobat x pro software
    buy windows 7 laptop canada
    windows 7 ultimate student discount full version
    where can i purchase microsoft office professional 2007
    adobe flash cs6 student discount
    pricing adobe acrobat

  22. It is perfect time to make some plans for the future and it is time to be happy.
    I have read this post and if I could I desire to suggest you few interesting things
    or advice. Maybe you could write next articles referring to this article.
    I want to read more things about it!

  23. JoshuaFasia说:

    viagra prescriptions over internet http://viagrawithoutdocpresc.accountant/#3086 – viagra prescriptions over internet

  24. agoriarat说:

    Ce type est plus léger que toute autre technologie d’absorption des chocs dans l’histoire de Nike. Adidas ZX 700 Homme Stetson, le fils d’un chapelier, remarqua que la tête ne convenait pas, il décida de confectionner un chapeau plus fonctionnel. La hauteur de bonne qualité, la performance globale extrêmement idéale, les baskets athlétiques Nike de qualité supérieure et les baskets Nike sont largement utilisées dans le monde entier. Comme le quartier Air Max, une unité Max Air et Phylon sont utilisés dans la semelle intercalaire. Les hommes de personne chacun une personne est certainement familiarisé avec Nike Air Max! Idéal maintenant, nous regardons approprié ici parmi les produits dans la marque de frères et s?urs de Nike Air Nike Air Huarache Max 2010 qui, le tout nouveau Nike Atmosphère traditionnelle BW! On dirait que j’aime AM90! Le dernier juste un sur ce fabricant, néanmoins, un certain nombre de nouvelles méthodes de couleur superbe ont tendance à être le suivant pour fournir l’utilisation apparaissent, Découvrez tous les! Les débouchages foncés avec une feuille tissée se réunissent pour produire la majorité des tiges réelles! La semelle intercalaire blanchie réelle obtiendra une assistance pendant le contour de l’?illet et aussi la bande qui entoure l’ensemble des chaussures. Essentiellement, cela signifie que les réductions réduites Asics Gel Livraison Rapide Pas Cher sont considérées comme étant à l’étape de l’entrée.
    xlccl20180412er

  25. Fitty说:

    Услуги по оценке недвижимости для суда – http://ocexp.ru

  26. I am sure this post has touched all the internet viewers,
    its really really pleasant piece of writing on building
    up new blog.

  27. agoriarat说:

    Any negotiations ought to occur before wholesale nfl jerseys nike you comply with employ the service of the law firm. So usually do not delay in preserving it. I would choose to blame his liberty to terrorize the city on some certain Decide but it surely goes way past that. He initial unveiled general public area goods over the AMIGA and C64 laptop or computer devices during the late 1970’s-80’s. While not one, even Philadelphia 76ers so, your risk of getting sued by the opposing party for failure to disclose info will increase. The proprietors in the 31 Therapeutic massage Envy spas and clinics situated in the new Jersey location constantly perform alongside one another to offer deluxe, nevertheless very affordable massage remedy and wholesale nba jerseys free shipping working day spa expert services for their area communities.
    xlddl20180412er

  28. I have been browsing online more than 3 hours today, yet I never found
    any interesting article like yours. It’s pretty worth enough
    for me. In my view, if all site owners and bloggers made good
    content as you did, the net will be a lot more useful than ever before.

  29. I’ve been surfing online more than 3 hours lately,
    but I never found any fascinating article like yours.

    It is pretty worth sufficient for me. In my opinion, if
    all website owners and bloggers made good content material
    as you did, the net will probably be much more
    helpful than ever before.

  30. faf说:

    Промышленный образец судебная и экспертная практика – http://patexp.ru

  31. Whoa! This blog looks exactly like my old
    one! It’s on a totally different topic but it has pretty
    much the same layout and design. Excellent choice of colors!

  32. Adobe Flash说:

    See How to Increase Client Value with Microsoft Dynamics CRM. discount 80%!

    windows 7 educational discount canada
    autocad lt 2016 price in uae
    windows 7 professional 64 bit download usb
    buy autodesk revit 2013
    adobe photoshop cs6 extended
    purchase adobe indesign software
    autocad lt 2016 software price in india
    buy autodesk
    photoshop cs3 price australia
    buy adobe illustrator cs6 cheap
    windows 7 professional amazon.ca

发表评论

电子邮件地址不会被公开。 必填项已用*标注