当前位置: 首页 > news >正文

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 openif (socket.readyState === WebSocket.OPEN) {// Send the list of product IDs through the WebSocket connectionsocket.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 openupdateAndSendProductIds(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)){//反序列化和构造函数冲突,改造了一下CatalogCatalog 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);}}
}

http://www.lryc.cn/news/274262.html

相关文章:

  • 数据结构第六弹---带头双向循环链表
  • 洛谷——P1347 排序(图论-拓扑排序)
  • JVM内存管理
  • 将 Python 和 Rust 融合在一起,为 pyQuil® 4.0 带来和谐
  • Spring Boot应用程序中VO的理解及使用
  • 华为交换机ETH-TRUNK链路聚合lacp模式与手工模式
  • 函数图像化
  • gnu工程的编译 - 以libiconv为例
  • 在 CentOS 7.8 上安装 Node.js
  • 【数据分析实战】冰雪大世界携程景区评价信息情感分析采集词云
  • BIND-DNS配置介绍
  • Python技巧
  • 几种常见的CSS三栏布局?介绍下粘性布局(sticky)?自适应布局?左边宽度固定,右边自适应?两种以上方式实现已知或者未知宽度的垂直水平居中?
  • 箭头函数 - JavaScript的新宠儿
  • 操作系统期末复习知识点
  • [英语学习][23][Word Power Made Easy]的精读与翻译优化
  • 吉林大学19、21级计算机学院《计算机网络》期末真题试题
  • python练习3【题解///考点列出///错题改正】
  • LINUX服务器防火墙nf_conntrack问题一例
  • 经典八股文之RocketMQ
  • Pandas之从sql库中导入数据的几种方法分析
  • 18. Mysql 存储过程,实现动态数据透视
  • VuePress部署到GitHub Pages
  • git 本地仓库
  • Hive实战:分科汇总求月考平均分
  • 快速搭建知识付费小程序,3分钟即可开启知识变现之旅
  • 【计算机图形学划重点】第一讲-Pipeline and Introduction
  • 面试题-DAG 有向无环图
  • vite + vue3引入ant design vue 报错
  • 使用EasyPoi导入数据并返回失败xls