Websocket实时更新商品信息

产品展示页面中第一次通过接口去获取数据库的列表数据

/// <summary>
/// 获取指定的商品目录
/// </summary>
/// <param name="pageSize"></param>
/// <param name="pageIndex"></param>
/// <param name="ids"></param>
/// <returns></returns>
[HttpGet]
[Route("items")]
[ProducesResponseType(typeof(PaginatedViewModel<Catalog>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(IEnumerable<ProductDto>), StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Catalogs([FromQuery] int pageSize = 10, [FromQuery] int pageIndex = 0, string ids = null)
{
    if (!string.IsNullOrEmpty(ids))
    {
        var items = await GetItemByIds(ids);
        if (!items.Any())
        {
            return BadRequest("ids value invalid. Must be comma-separated list of numbers");
        }

        return Ok(items);
    }

    var totalItems = await _catalogContext.Catalogs
        .LongCountAsync();

    var itemsOnPage = await _catalogContext.Catalogs
        .OrderBy(c => c.Name)
        .Skip(pageSize * pageIndex)
        .Take(pageSize)
        .ToListAsync();
    var result = itemsOnPage.Select(x => new ProductDto(x.Id.ToString(), x.Name, x.Price.ToString(), x.Stock.ToString(), x.ImgPath));
    var model = new PaginatedViewModel<ProductDto>(pageIndex, pageSize, totalItems, result);
    return Ok(model);

}

2.在前端页面会把当前页面的产品列表id都发送到websocket中去

function updateAndSendProductIds(ids) {
    productIds = ids;
 
    // Check if the WebSocket is open
    if (socket.readyState === WebSocket.OPEN) {
        // Send the list of product IDs through the WebSocket connection
        socket.send(JSON.stringify(productIds));
    }
}
 
function fetchData() {
    
    const apiUrl = baseUrl + `/Catalog/items?pageSize=${pageSize}&pageIndex=${currentPage}`;
 
    axios.get(apiUrl)
        .then(response => {
            const data = response.data.data;
            displayProducts(baseUrl, data);
 
            const newProductIds = data.map(product => product.Id);
            // Check if the WebSocket is open
            updateAndSendProductIds(newProductIds);
            // 从响应中获取总页数
            const totalPages = Math.ceil(response.data.count / pageSize);
            displayPagination(totalPages);
 
            // 更新当前页数的显示
            const currentPageElement = document.getElementById('currentPage');
            currentPageElement.textContent = `当前页数: ${currentPage + 1} / 总页数: ${totalPages}`;
        })
        .catch(error => {
            console.error('获取数据失败:', error);
        });
}
using System.Net.WebSockets;
using System.Threading.Tasks;
using System;
using WsServer.Handler;
using WsServer.Manager;
using StackExchange.Redis;
using Microsoft.Extensions.Configuration;
using System.Collections.Generic;
using Catalogs.Domain.Catalogs;
using Catalogs.Domain.Dtos;
using System.Net.Sockets;
 
namespace WebScoket.Server.Services
{
    /// <summary>
    /// 实时推送产品主要是最新的库存,其他信息也会更新
    /// </summary>
    public class ProductListHandler : WebSocketHandler
    {
        private System.Threading.Timer _timer;
        private readonly IDatabase _redisDb;
        //展示列表推送
        private string productIdsStr;
        public ProductListHandler(WebSocketConnectionManager webSocketConnectionManager,IConfiguration configuration) : base(webSocketConnectionManager)
        {
            ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configuration["DistributedRedis:ConnectionString"] ?? throw new Exception("$未能获取distributedredis连接字符串"));
            _redisDb = redis.GetDatabase();
            _timer = new System.Threading.Timer(Send, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
        }
        private void Send(object state)
        {
            // 获取当前时间并发送给所有连接的客户端
            if (productIdsStr != null)
            {
                string[] productIds = System.Text.Json.JsonSerializer.Deserialize<string[]>(productIdsStr);
                string hashKeyToRetrieve = "products";
                List<ProductDto> products = new List<ProductDto>();
 
                foreach (var productId in productIds)
                {
                    if(productId == "null") {
                        continue;
                    }
                    string retrievedProductValue = _redisDb.HashGet(hashKeyToRetrieve, productId);
                    if (!string.IsNullOrEmpty(retrievedProductValue))
                    {
                        //反序列化和构造函数冲突,改造了一下Catalog
                        Catalog catalog = System.Text.Json.JsonSerializer.Deserialize<Catalog>(retrievedProductValue);
                        products.Add(new ProductDto(catalog.Id.ToString(), catalog.Name, catalog.Price.ToString(), catalog.Stock.ToString(), catalog.ImgPath));
                    }
                }
                if (products.Count > 0)
                {
                     SendMessageToAllAsync(System.Text.Json.JsonSerializer.Serialize(products)).Wait();
                }
                else
                {
                    SendMessageToAllAsync("NoProduct").Wait();
                }
            }
        }
        public override async Task ReceiveAsync(WebSocket socket, WebSocketReceiveResult result, byte[] buffer)
        {
            //每次页面有刷新就会拿到展示的id列表
            productIdsStr = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
        }
    }
}

相关推荐

  1. Websocket实时更新商品信息

    2024-01-06 08:48:04       50 阅读
  2. 【Pyhton爬虫实战】爬取京东商城商品信息

    2024-01-06 08:48:04       34 阅读
  3. Django中如何使用WebSocket实时更新数据?

    2024-01-06 08:48:04       32 阅读
  4. ESP32网络编程实例-WebSocket服务器广播信息

    2024-01-06 08:48:04       69 阅读
  5. 条形码获取商品信息

    2024-01-06 08:48:04       32 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-06 08:48:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-06 08:48:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-01-06 08:48:04       87 阅读
  4. Python语言-面向对象

    2024-01-06 08:48:04       96 阅读

热门阅读

  1. Spring Boot和Spring主要区别:

    2024-01-06 08:48:04       60 阅读
  2. k8s-二进制部署

    2024-01-06 08:48:04       51 阅读
  3. Ubuntu20.04安装suiteCRM

    2024-01-06 08:48:04       56 阅读
  4. 使用conda管理Python虚拟环境

    2024-01-06 08:48:04       61 阅读
  5. conda

    conda

    2024-01-06 08:48:04      58 阅读
  6. conda创建、查看、删除虚拟环境

    2024-01-06 08:48:04       57 阅读
  7. 从0开始的编程生活

    2024-01-06 08:48:04       54 阅读
  8. Sentinel 使用

    2024-01-06 08:48:04       52 阅读
  9. EasyExcel的追加写入(新增POI、CSV)

    2024-01-06 08:48:04       56 阅读
  10. 使用Android 协程代替Handler

    2024-01-06 08:48:04       51 阅读