Fork me on GitHub
简单的.NET 8 Web API使用Redis发布订阅模式,示例api示例
简单的.NET 8 Web API使用Redis 发布订阅模式,示例api示例
  • Redis
// WeatherForecastController.cs
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;

namespace WebApiDemo
{
    [ApiController]
    [Route("[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly IConnectionMultiplexer _redis;

        public WeatherForecastController(IConnectionMultiplexer redis)
        {
            _redis = redis;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            var forecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            }).ToArray();

            // 发布消息到Redis频道
            var db = _redis.GetDatabase();
            foreach (var forecast in forecasts)
            {
                db.Publish("weatherUpdates", $"{forecast.Date}: {forecast.Summary}");
            }

            return forecasts;
        }
    }
}

  

在这个示例中,我们在WeatherForecastController中注入了一个IConnectionMultiplexer实例,它用于与Redis进行通信。在Get方法中,我们生成了天气预报数据,并且使用Redis的发布功能,将每条天气预报信息发布到名为"weatherUpdates"的频道中。

在Startup.cs中,需要添加对Redis的连接配置和注册服务:

// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;

namespace WebApiDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // 注册Redis连接
            services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost"));
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

  这样,当调用Get方法时,会生成天气预报数据并发布到Redis的"weatherUpdates"频道中。其他订阅了该频道的客户端将会收到相应的消息。

// WeatherUpdatesSubscriber.cs
using StackExchange.Redis;
using System;

namespace WebApiDemo
{
    public class WeatherUpdatesSubscriber
    {
        private readonly IConnectionMultiplexer _redis;

        public WeatherUpdatesSubscriber(IConnectionMultiplexer redis)
        {
            _redis = redis;
        }

        public void SubscribeToWeatherUpdatesChannel()
        {
            ISubscriber subscriber = _redis.GetSubscriber();
            subscriber.Subscribe("weatherUpdates", (channel, message) =>
            {
                Console.WriteLine($"Received weather update: {message}");
            });
        }
    }
}

  

在这个示例中,我们创建了一个名为WeatherUpdatesSubscriber的类,它负责订阅Redis的"weatherUpdates"频道,并在接收到消息时打印出来。

接下来,在Startup.cs中注册WeatherUpdatesSubscriber服务,并在应用启动时调用SubscribeToWeatherUpdatesChannel方法:

// Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StackExchange.Redis;

namespace WebApiDemo
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // 注册Redis连接
            services.AddSingleton<IConnectionMultiplexer>(ConnectionMultiplexer.Connect("localhost"));
            // 注册WeatherUpdatesSubscriber服务
            services.AddSingleton<WeatherUpdatesSubscriber>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, WeatherUpdatesSubscriber weatherUpdatesSubscriber)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            // 在应用启动时订阅Redis频道
            weatherUpdatesSubscriber.SubscribeToWeatherUpdatesChannel();
        }
    }
}

  这样,当应用启动时,WeatherUpdatesSubscriber服务会订阅Redis的"weatherUpdates"频道,一旦有新消息发布到该频道,就会在控制台中打印出相应的天气更新信息。

 

posted on 2024-01-16 22:11  HackerVirus  阅读(362)  评论(0)    收藏  举报