当前位置: 移动技术网 > IT编程>开发语言>.net > .net core使用ocelot---第一篇 简单使用

.net core使用ocelot---第一篇 简单使用

2019年08月08日  | 移动技术网IT编程  | 我要评论

坐月子可以洗头发吗,茵佳妮服饰,新型节能取暖设备

简介

  接下来你会学习,基于asp.net core 用ocelot实现一个简单的api网关。或许你会疑问什么是api网关,我们先看下面的截图

  

  api网关是访问你系统的入口,它包括很多东西,比如路由(routing),身份验证(authentication),服务发现(service discovery),日志(logging ),等等。

ocelot

     ocelot提供统一的访问入口,适用于.net开发的微服务或者开发的面向服务架构,可以访问ocelot获得更多信息。

     我会用ocelot实现一个简单的例子。

step1

    先创建三个项目,如下所示。

项目名称

项目类型

描述

apigateway

asp.net core empty

demo的入口

customersapiservices

asp.net core web api

api service消费者相关操作

productsapiservices

asp.net core web api

api service 产品相关操作

 

 

step2

     创建两个api services,在custimersapiservices项目中创建customerscontroller。

[route("api/[controller]")]  
public class customerscontroller : controller  
{          
    [httpget]  
    public ienumerable<string> get()  
    {  
        return new string[] { "catcher wong", "james li"     };  
    }  
  
    [httpget("{id}")]  
    public string get(int id)  
    {  
        return $"catcher wong - {id}";  
    }              
}  

 

 为了确定custimersapiservices的应用url,我们应该在项目的类中添加useurls

public static iwebhost buildwebhost(string[] args) =>  
        webhost.createdefaultbuilder(args)  
            .usestartup<startup>()  
            .useurls("http://localhost:9001")  
            .build();  

 

 在priductsapiservices项目中新建productscontroller

[route("api/[controller]")]  
public class productscontroller : controller  
{  
    [httpget]  
    public ienumerable<string> get()  
    {  
        return new string[] { "surface book 2", "mac book pro" };  
    }  
}

 

  

 同样在项目的类中添加useurls

 

public static iwebhost buildwebhost(string[] args) =>  
        webhost.createdefaultbuilder(args)  
            .usestartup<startup>()  
            .useurls("http://localhost:9002")  
            .build(); 

 

注意

    你可以通过项目的属性对应用的url进行配置。

  

step3

    运行custimersapiservices 和productsapiservices。打开两个cmd终端,cd到两个服务的文件夹位置,输入 "dotnet run" 启动两个项目。

 运行成功如下所示。

step4

    接下来我们新建 apigateway项目,首先安装ocelot安装包。

install-package ocelot

     安装成功后,如下图所示。

 

step5

       在项目下新建configuration.json如下所示。

{  
    "reroutes": [  
        {  
            "downstreampathtemplate": "/api/customers",  
            "downstreamscheme": "http",  
            "downstreamhost": "localhost",  
            "downstreamport": 9001,  
            "upstreampathtemplate": "/customers",  
            "upstreamhttpmethod": [ "get" ]  
        },  
        {  
            "downstreampathtemplate": "/api/customers/{id}",  
            "downstreamscheme": "http",  
            "downstreamhost": "localhost",  
            "downstreamport": 9001,  
            "upstreampathtemplate": "/customers/{id}",  
            "upstreamhttpmethod": [ "get" ]  
        },  
        {  
            "downstreampathtemplate": "/api/products",  
            "downstreamscheme": "http",  
            "downstreamport": 9002,  
            "downstreamhost": "localhost",  
            "upstreampathtemplate": "/api/products",  
            "upstreamhttpmethod": [ "get" ]  
        }  
    ],  
    "globalconfiguration": {  
        "requestidkey": "ocrequestid",  
        "administrationpath": "/administration"  
    }  
}  

  该文件是api网关的配置文件,包括两部分,reroutes和globalconfiguration。

  reroutes是告诉ocelot如何操作上游的request请求,

  globalconfiguration有点黑客的感觉,允许对reroutes的设置进行重写。

  用下面的片段介绍reroutes。

{  
    "downstreampathtemplate": "/api/customers/{id}",  
    "downstreamscheme": "http",  
    "downstreamhost": "localhost",  
    "downstreamport": 9001,  
    "upstreampathtemplate": "/customers/{id}",  
    "upstreamhttpmethod": [ "get" ]  
}  

 

  以downstream开头的项意味我们的请求会指向

  以upstream开头的项意味我们应该使用/customers/{id} 的http get请求去访问服务。

step6

       修改startup类,使用ocelot。

public class startup  
{  
    public startup(ihostingenvironment env)  
    {  
        var builder = new microsoft.extensions.configuration.configurationbuilder();  
        builder.setbasepath(env.contentrootpath)      
               //add configuration.json  
               .addjsonfile("configuration.json", optional: false, reloadonchange: true)  
               .addenvironmentvariables();  
  
        configuration = builder.build();  
    }  
  
    //change  
    public iconfigurationroot configuration { get; }  
  
    public void configureservices(iservicecollection services)  
    {  
        action<configurationbuildercachepart> settings = (x) =>  
        {  
            x.withmicrosoftlogging(log =>  
            {  
                log.addconsole(loglevel.debug);  
  
            }).withdictionaryhandle();  
        };  
        services.addocelot(configuration, settings);  
    }  
      
    //don't use task here  
    public async void configure(iapplicationbuilder app, ihostingenvironment env)  
    {  
        await app.useocelot();  
    }  
}  

 

  别忘了添加上面的configuration.json文件。

step7

       这一步至关重要,用来配置ocelot。

     我们新建iwebhostbuilder的新实例,不要使用var!!!

public class program  
{  
    public static void main(string[] args)  
    {  
        iwebhostbuilder builder = new webhostbuilder();  
        builder.configureservices(s =>  
        {  
            s.addsingleton(builder);  
        });  
        builder.usekestrel()  
               .usecontentroot(directory.getcurrentdirectory())  
               .usestartup<startup>()  
               .useurls("http://localhost:9000");  
  
        var host = builder.build();  
        host.run();  
    }  
}  

  同样我们需要指明应用的url。

step8

     启动apigateway,使用cmd通过dotnet run 命令。启动成功后,输入http://www.lhsxpumps.com/_localhost:9000

  当我们通过客户端访问http://localhost:9000/api/products真实的路由是http://localhost:9002/api/products

       当我们访问,真实的路由http://localhost:9001/api/customers

      当我们访问http://localhost:9000/customers/1, 真实的路由是。

源码:apigatewaydemo

百度网盘

链接:https://pan.baidu.com/s/17sqfgcyx8yehrl_lwkaula
提取码:p3d0

总结

       这篇文章介绍了通过ocelot创建api网关。希望可以帮到你。

     由于只是简单的示例代码,ocelot许多重要的特性比如服务发现,身份验证,服务质量(qos),未在示例中体现。

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网