(精华)2020年8月22日 微服务 Ocelot的简单使用(.net core版)

本文详细介绍了如何使用Ocelot作为微服务网关,实现API路由和转发。首先,通过创建一个包含学生信息的DemoProject,然后构建Ocelot项目进行路由配置,最后演示了如何通过Ocelot访问DemoProject中的数据。

一、创建demo项目

1.新建webapi项目,命名为“DemoProject”,去掉HTTPS勾选

using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace DemoProject.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DefaultController : ControllerBase
    {
        static List<Student> list = new List<Student>() {
             new Student(){ ID = "001", StudentName = "学生1", StudentAge = 16 },
             new Student(){ ID = "002", StudentName = "学生2", StudentAge = 18 },
             new Student(){ ID = "003", StudentName = "学生3", StudentAge = 17 }
         };

        [HttpGet]
        public List<Student> GetList()
        {
            return list;
        }

        [HttpGet]
        public Student GetModel(string id)
        {
            return list.Find(t => t.ID == id);
        }
    }

    public class Student
    {
        public string ID { get; set; }
        public string StudentName { get; set; }
        public int StudentAge { get; set; }
    }
}

2.通过VS启动,并且保证能正常访问
在这里插入图片描述
在这里插入图片描述

二、创建Ocelot项目

1.新建webapi项目,命名为“OcelotProject”,去掉HTTPS勾选,不需要Controller

2.打开程序包管理器控制台,执行命令:Install-Package Ocelot
在这里插入图片描述
3.在项目根目录下,新建配置文件“ocelot.json”,填写为你自己的“DemoProject”的端口号

{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/Default/GetList",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5963
        }
      ],
      "UpstreamPathTemplate": "/GetList",
      "UpstreamHttpMethod": [ "Get" ]
    },
    {
      "DownstreamPathTemplate": "/api/Default/GetModel?id={s1}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "localhost",
          "Port": 5963
        }
      ],
      "UpstreamPathTemplate": "/GetModel?id={s1}",
      "UpstreamHttpMethod": [ "Get" ]
    }
  ]
}

4.在Program.cs的CreateHostBuilder中加入

.ConfigureAppConfiguration(conf => {
    conf.AddJsonFile("ocelot.json", false, true);
})

在这里插入图片描述
5.找到Startup.cs

在ConfigureServices中加入:

services.AddOcelot(Configuration);

在Configure中加入:

app.UseOcelot().Wait();

在这里插入图片描述

三、请求

通过VS启动“OcelotProject”,由于配置中对外的路由为“/GetList”,所以访问地址为:http://ip:port/GetList
在这里插入图片描述
GetModel的访问地址为:http://ip:port/GetModel?id=002

在这里插入图片描述

代码:https://files.cnblogs.com/files/shousiji/OcelotDemo.rar

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愚公搬代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值