什么是redis
REmote DIctionary Server(Redis) 是一个由 Salvatore Sanfilippo 写的 key-value 存储系统,是跨平台的非关系型数据库。
Redis 是一个开源的使用 ANSI C 语言编写、遵守 BSD 协议、支持网络、可基于内存、分布式、可选持久性的键值对(Key-Value)存储数据库,并提供多种语言的 API。
Redis 通常被称为数据结构服务器,因为值(value)可以是字符串(String)、哈希(Hash)、列表(list)、集合(sets)和有序集合(sorted sets)等类型。
开始实战
我们以商品服务举例,在商品服务中,提供了一个商品列表接口,如下图。
代码如下。
/// <summary>
/// 获取商品列表
/// </summary>
/// <returns></returns>
[HttpGet]
public Response<List<GoodsListView>> GetList()
{
var result = new Response<List<GoodsListView>>();
try
{
result.Result = _goodsApp.GetList();
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
_goodsApp.GetList()
这里就是去查询数据库了。 这样写的话,每一次的请求都需要查询数据库,接下来就拿这个接口进行改造。
首先电脑里需要先安装redis,网上很多资源很详细了,不在过多说明,可以参考下菜鸟教程。https://www.runoob.com/redis/redis-install.html,
若需要可视化客户端的,网上也有很多,这里列一个我经常使用的。
免费开源的,也挺好用 地址在这里https://github.com/qishibo/AnotherRedisDesktopManager/releases/tag/v1.4.2。
然后接着在项目里引用redis,首先需要安装nuget包。
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="5.0.1" />
接着在appsetting.json
里配置下redis地址和端口号。
"RedisServer": "127.0.0.1:6379"
然后需要在startup.cs
里引用下redis。
services.AddStackExchangeRedisCache(options => options.Configuration = Configuration.GetConnectionString("RedisServer"));
好了,到目前为止,配置项已经全部完成了,接下开开始进行接口改造,找到上面的获取商品列表的接口,改造如下。
using EasyShop.GoodsService.App.Interface;
using EasyShop.GoodsService.Response;
using Infrastructure;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;
namespace EasyShop.GoodsService.Controllers
{
[ApiController]
[Route("api/[controller]/[action]")]
public class GoodsController : ControllerBase
{
private readonly IGoodsApp _goodsApp;
private readonly IDistributedCache _cache;
public GoodsController(IGoodsApp goodsApp,IDistributedCache cache)
{
_goodsApp = goodsApp;
_cache = cache;
}
/// <summary>
/// 获取商品列表
/// </summary>
/// <returns></returns>
[HttpGet]
public Response<List<GoodsListView>> GetList()
{
const string cacheKey = "goods_list";
var result = new Response<List<GoodsListView>>();
try
{
//查询redis
var goodsListJson = _cache.GetString(cacheKey);
if (goodsListJson == null)
{
//redis不存在,则查询库,之后把值放入redis
result.Result = _goodsApp.GetList();
var json = JsonConvert.SerializeObject(result.Result);
_cache.SetString(cacheKey, json);
}
else
{
var goodsList = JsonConvert.DeserializeObject<List<GoodsListView>>(goodsListJson);
result.Result = goodsList;
}
}
catch (Exception ex)
{
result.Code = 500;
result.Message = ex.InnerException?.Message ?? ex.Message;
}
return result;
}
}
}
从上面的代码可以看出来,请求进来的时候,先去通过cacheKey
去查询redis中存不存在对应的值,若存在则直接解析后返回,若不存在则去查询数据库,查询之后,把结果转成json,保存在redis中。
结语
这里的redis使用的比较简单,感兴趣的可以继续研究。
项目地址:https://gitee.com/limeng66/easy-shop