上一篇讲解了Redis的搭建及ServiceStack.Redis 与 StackExchange.Reids 的区别https://blog.csdn.net/qq_39569480/article/details/105249607
这篇文章遗我们来说下 StackExchange.Redis的使用及帮助类
首先在windows上安装redis 在上边连接中有教程
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using ServiceStack.Redis;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
namespace qq.Web.Host.Helper
{
public class RedisClient
{
static ConnectionMultiplexer redis = null;
IDatabase db = null;
public void InitConnect(IConfiguration Configuration)
{
try
{
var RedisConnection = Configuration.GetConnectionString("RedisConnectionString");
redis = ConnectionMultiplexer.Connect(RedisConnection);
db = redis.GetDatabase();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
redis = null;
db = null;
}
}
public RedisClient( )
{
}
#region String
///
/// 保存单个key value
///
/// 保存的值
/// 过期时间
public bool SetStringKey(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
return db.StringSet(key, value, expiry);
}
///
/// 获取单个key的值
///
public RedisValue GetStringKey(string key)
{
return db.StringGet(key);
}
///
/// 获取一个key的对象
///
public T GetStringKey(string key)
{
if (db == null)
{
return default;
}
var value = db.StringGet(key);
if (value.IsNullOrEmpty)
{
return default;
}
return JsonConvert.DeserializeObject(value);
}
///
/// 保存一个对象
///
///
public bool SetStringKey(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
if (db == null)
{
return false;
}
string json = JsonConvert.SerializeObject(obj);
return db.StringSet(key, json, expiry);
}
#endregion
///
/// 将一个泛型List添加到缓存中
///
/// 泛型T
/// Key
/// list
/// 数据库序号,不传默认为0
///
public bool addList(string listkey, List list, int db_index = 0)
{
if (db == null)
{
return false;
}
var value = JsonConvert.SerializeObject(list);
return db.StringSet(listkey, value);
}
///
/// 通过指定Key值获取泛型List
///
/// 泛型T
/// Key
/// 数据库序号,不传默认为0
///
public List getList(string listkey, int db_index = 0)
{
//var db = redis.GetDatabase(db_index);
if (db == null)
{
return new List();
}
if (db.KeyExists(listkey))
{
var value = db.StringGet(listkey);
if (!string.IsNullOrEmpty(value))
{
var list = JsonConvert.DeserializeObject>(value);
return list;
}
else
{
return new List();
}
}
else
{
return new List();
}
}
public bool getKeyExists(string listkey, int db_index = 0)
{
if (db == null)
{
return false;
}
if (db.KeyExists(listkey))
{
return true;
}
else
{
return false;
}
}
///
/// 删除指定List中满足条件的元素
///
/// Key
/// lamdba表达式
/// 数据库序号,不传默认为0
///
public bool delListByLambda(string listkey, Func func, int db_index = 0)
{
if (db == null)
{
return false;
}
if (db.KeyExists(listkey))
{
var value = db.StringGet(listkey);
if (!string.IsNullOrEmpty(value))
{
var list = JsonConvert.DeserializeObject>(value);
if (list.Count > 0)
{
list = list.SkipWhile(func).ToList();
value = JsonConvert.SerializeObject(list);
return db.StringSet(listkey, value);
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
return false;
}
}
///
/// 获取指定List中满足条件的元素
///
/// Key
/// lamdba表达式
/// 数据库序号,不传默认为0
///
public List getListByLambda(string listkey, Func func, int db_index = 0)
{
if (db == null)
{
return new List();
}
if (db.KeyExists(listkey))
{
var value = db.StringGet(listkey);
if (!string.IsNullOrEmpty(value))
{
var list = JsonConvert.DeserializeObject>(value);
if (list.Count > 0)
{
list = list.Where(func).ToList();
return list;
}
else
{
return new List();
}
}
else
{
return new List();
}
}
else
{
return new List();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace qqq.Web.Host.Helper
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//初始化redis
RedisClient.redisClient.InitConnect(Configuration);//*******
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
using System;using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
namespace qqq.Web.Host.Helper
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
// GET api/values/5
[HttpGet]
public ActionResult Get(int id)
{
var redisResult = RedisClient.redisClient.GetStringKey("key1");
//若redis没有数据,则取数据并设置redis
if (redisResult == null || redisResult == default(int))
{
Console.WriteLine("redisResult is empty");
RedisClient.redisClient.SetStringKey("key1", id.ToString());
return id.ToString();
}
return redisResult.ToString();//有则直接返回
}
[HttpGet]
public ActionResult GetList(string 简称, int 开始索引, int 限定数量) {
try
{//缓存中如果存在这个key返回查出的数据 如果不存在则写入缓存 查出数据后进行条件筛选和分页
List 列表 = null;
if (RedisClient.redisClient.getKeyExists("123"))
{
列表 = RedisClient.redisClient.getList("123");
}
else
{
RedisClient.redisClient.addList("123", GetDrugList());//插入key 和集合
列表 = RedisClient.redisClient.getList("123");
}
if (!string.IsNullOrEmpty(简称))
{
列表 = 列表.Where(x => x.首字母缩写.Contains(简称)).ToList();
}
if (列表.Count < 限定数量)
{
return Json(new { ok = false, msg = "sucess", data = 列表.GetRange(开始索引, 列表.Count) });
}
return Json(new { ok = false, msg = "sucess", data = 列表.GetRange(开始索引, 限定数量) });
}
catch (Exception ex)
{
return Json(new { ok = false, msg = ex.Message, data = "" });
}
}
}
}
F5运行,输入:https://localhost:5001/api/values/100
返回100,此时redis中的数据库已经存入了 key1,100.
再次访问https://localhost:5001/api/values/99,还是会返回100,因为已经从redis中取数据了