aspnetcore使用websocket实时更新商品信息
先演示一下效果,再展示代码逻辑。


中间几次调用过程省略。。。
暂时只用到了下面四个项目

1.产品展示页面中第一次通过接口去获取数据库的列表数据
/// <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);
});
}
3.websocket拿到了id数据可以精确的把当前页面的产品都查出来再推送给product.html页面,通过下面的ReceiveAsync方法获取html发送的数据,再通过timer定时器每秒钟Send方法实时的往页面发送获取到的数据,当然这个是不断的去从redis中去查的。
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);
}
}
}
4.html页面就可以拿到最新数据再去绑定到页面
socket.addEventListener('message', (event) => {
if (event.data == "NoProduct") {
clearProductList();
}
// Handle the received product data and update the product list
const productData = JSON.parse(event.data);
// Update the product list with the received data (call your displayProducts function)
displayProducts(baseUrl, productData);
});
整个流程就这么简单,但是这里需要保持数据库和redis的数据实时同步,否则页面展示的就不是最新的数据就没意义了。
再回到Catalog.Service服务中。
private async Task DeleteCache()
{
//await _redisDb.HashDeleteAsync("products",id); //没必要了
await _channel.Writer.WriteAsync("delete_catalog_fromredis");
}
再做更新、新增、删除等动作的时候就调用一下DeleteCache方法,往后台服务发送一个channel,当后台收到后就做redis删除并且从初始化sqlserver到redis列表同步的操作
using System.Reflection;
using System.Threading.Channels;
using Catalogs.Infrastructure.Database;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using StackExchange.Redis; namespace Catalogs.WebApi.BackgroudServices
{
/// <summary>
/// 记得任何删除了或者购买了产品后需要删除改产品的键
/// </summary>
public class InitProductListToRedisService : BackgroundService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IDatabase _redisDb;
private readonly Channel<string> _channel;
private readonly ILogger _logger;
public InitProductListToRedisService(IServiceScopeFactory serviceScopeFactory, IConfiguration configuration, Channel<string> channel, ILogger<InitProductListToRedisService> logger)
{
_serviceScopeFactory = serviceScopeFactory;
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(configuration["DistributedRedis:ConnectionString"] ?? throw new Exception("$未能获取distributedredis连接字符串"));
_redisDb = redis.GetDatabase();
_channel = channel;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await Init(); while (!_channel.Reader.Completion.IsCompleted)
{
var msg = await _channel.Reader.ReadAsync();
if(msg == "delete_catalog_fromredis")
{
await Init();
}
}
} private async Task Init()
{
using var scope = _serviceScopeFactory.CreateScope();
try
{
CatalogContext _context = scope.ServiceProvider.GetRequiredService<CatalogContext>();
string hashKey = "products";
var products = await _context.Catalogs.ToListAsync(); await _redisDb.KeyDeleteAsync(hashKey); foreach (var product in products)
{ string productField = product.Id.ToString();
string productValue = System.Text.Json.JsonSerializer.Serialize(product); _redisDb.HashSet(hashKey, new HashEntry[] { new HashEntry(productField, productValue) });
} _logger.LogInformation($"ProductList is over stored in Redis Hash.");
}
catch(Exception ex)
{
_logger.LogError($"ProductLis stored in Redis Hash error.");
}
}
}
}
这里还有优化的空间可以只针对怕products的hashset的某个id去更新、删除、新增一条数据。
示例代码:
liuzhixin405/efcore-template (github.com)
aspnetcore使用websocket实时更新商品信息的更多相关文章
- WebSocket 实时更新mysql数据到页面
使用websocket的初衷是,要实时更新mysql中的报警信息到web页面显示 没怎么碰过web,代码写的是真烂,不过也算是功能实现了,放在这里也是鞭策自己,web也要多下些功夫 准备 引入依赖 & ...
- HTML5 WebSocket 实时推送信息测试demo
测试一下HTML5的websocket功能,实现了客户端→服务器实时推送信息到客户端,包括推送图片: websocket实现MessageInbound类 onTextMessage()/onBina ...
- C#Winform实时更新数据库信息Demo(使用Scoket)
最近在贴吧上看到有个提问就是关于怎么在Winform上实时的更新数据 提问者提到的是利用Timer去轮询,但最后经过网上查了下资料,感觉Socket也是可行的, 于是就写了这个Demo 这个Demo的 ...
- 第十二章——SQLServer统计信息(1)——创建和更新统计信息
原文:第十二章--SQLServer统计信息(1)--创建和更新统计信息 简介: 查询的统计信息: 目前为止,已经介绍了选择索引.维护索引.如果有合适的索引并实时更新统计信息,那么优化器会选择有用的索 ...
- web页面实时更新页面的原理--WebSocket
原文:https://www.jianshu.com/p/8f956cd4d42b angular-cli启动的项目也可以自动刷新,底下应该也是应用的websocket的原理. ----------- ...
- 使用Node.js+Socket.IO搭建WebSocket实时应用
Web领域的实时推送技术,也被称作Realtime技术.这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新.它有着广泛的应用场景,比如在线聊天室.在线客服系统.评论系统.WebIM等. W ...
- (转)使用Node.js+Socket.IO搭建WebSocket实时应用
Web领域的实时推送技术,也被称作Realtime技术.这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新.它有着广泛的应用场景,比如在线聊天室.在线客服系统.评论系统.WebIM等. W ...
- Web网站数据”实时”更新设计
请注意这个实时打上了双引号,没有绝对的实时,只是时间的颗粒不一样罢了(1ms,1s,1m). 服务器数据有更新可以快速通知客户端.Web 基于取得模式,而服务器建立大量的和客户端连接来提供数据实时更新 ...
- 使用Node.js+Socket.IO搭建WebSocket实时应用【转载】
原文:http://www.jianshu.com/p/d9b1273a93fd Web领域的实时推送技术,也被称作Realtime技术.这种技术要达到的目的是让用户不需要刷新浏览器就可以获得实时更新 ...
- 【用户交互】APP没有退出前台但改变系统属性如何实时更新UI?监听系统广播,让用户交互更舒心~
前日,一小伙伴问我一个问题,说它解决了半天都没解决这个问题,截图如下: 大概楼主理解如下: 如果在应用中有一个判断wifi的开关和一个当前音量大小的seekbar以及一个获取当前电量多少的按钮,想知道 ...
随机推荐
- Teamcenter RAC 开发之《新建Item》
private TCComponentItem createOperation(String itemName,String itemType) { //obejct_name itemType tr ...
- 9.2 运用API实现线程同步
Windows 线程同步是指多个线程一同访问共享资源时,为了避免资源的并发访问导致数据的不一致或程序崩溃等问题,需要对线程的访问进行协同和控制,以保证程序的正确性和稳定性.Windows提供了多种线程 ...
- Redis系列之——使用常见问题
文章目录 一 子进程开销和优化 二 fork操作 三 aof追加阻塞 一 子进程开销和优化 1 cpu 开销:rdb和aof文件生成,属于cpu密集型 优化:不做cpu绑定,不和cpu密集型的服务一起 ...
- vscode没有完全汉化怎么办? vs code部分内容没汉化的解决办法
- 开源项目 | 一款基于NodeJs+Vue3的强大的在线设计图片工具
一.项目概述 一款漂亮且功能强大的在线海报图片设计器,仿稿定设计.适用于海报图片生成.电商分享图.文章长图.视频/公众号封面等多种场景. 二. 技术特性 丝滑的操作体验,丰富的交互细节,基础功能完善 ...
- AI图形算法的应用之一:仪表识别
目前AI智能算法如火如荼,各大型厂商对此趋之若鹜般加大开发力度,比如大华.海康这些视频处理类,以及百度.腾讯这些IT软件厂商,因为业务开展需要,我也把研发方向转向于此,小有成绩,在此展示一下. 最近研 ...
- [ABC212E] Safety Journey 题解
Safety Journey 题目大意 给定一张缺少了 \(m\) 条边的 \(n\) 个点的完全图和一个正整数 \(k\),你需要求出满足以下条件的序列 \(A\) 的数量: \(A\) 的长度为 ...
- Unity anchoredPosition转localPosition
参考 https://zhuanlan.zhihu.com/p/119442308 在已经有结果的情况下,先捋一下unity对相关字段的注释就能得出很多公式 (rectMinPos表示左下角在父节点坐 ...
- 一个简单高效低内存的.NET操作Excel开源框架 - MiniExcel
前言 日常工作中经常与数据打交道的同学肯定会难以避免对Excel的一些数据操作如导入.导出等,但是当对一些大数据量操作Excel时经常会遇到一个常见的问题内存溢出.今天给大家推荐一个简单.高效.低内存 ...
- WebSocket connection to 'ws://127.0.0.1:8089/websocket/0,1,10,admin' failed:
WebSocket连接失败 背景: 相同项目数据库从mysql变更到sqlite,代码层面基本没有变更,但是WebSocket连接失败,查找多方原因,未找到问题,最后发现新项目JDK为OpenJDK, ...