一、前端客服代码

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>LayIM测试</title>
<link rel="stylesheet" href="./layui/css/layui.css" media="all">
<link rel="stylesheet" href="./contextMenu/contextMenu.css">
</head>
<body>
<script src="./layui/layui.js"></script>
<script>
layui.config({
base: './contextMenu/' //扩展 JS 所在目录
,version: true
}).extend({
ext: 'contextMenu'
});
//演示代码
layui.use('layim', function(layim){
var layim = layui.layim;
layim.config({
init: {
//配置客户信息
mine: {
"username": "访客" //我的昵称
,"id": "100000123" //我的ID
,"status": "online" //在线状态 online:在线、hide:隐身
,"remark": "在深邃的编码世界,做一枚轻盈的纸飞机" //我的签名
,"avatar": "//res.layui.com/images/fly/avatar/00.jpg" //我的头像
}
}
//开启客服模式
,brief: true
});
//打开一个客服面板
layim.chat({
name: '在线客服一' //名称
,type: 'kefu' //聊天类型
,avatar: '//tp1.sinaimg.cn/5619439268/180/40030060651/1' //头像
,id: 1111111 //定义唯一的id方便你处理信息
}).chat({
name: '在线客服二' //名称
,type: 'kefu' //聊天类型
,avatar: '//tp1.sinaimg.cn/5619439268/180/40030060651/1' //头像
,id: 2222222 //定义唯一的id方便你处理信息
});
layim.setChatMin(); //收缩聊天面板
});
</script>
</body>
</html>

二、在.Net Core 2.1中使用

1、安装依赖包:Nugget: StackExchange.Redis

2、新建Helper类库,并添加RedisHelper.cs类

    public class RedisHelper
{
private ConnectionMultiplexer Redis { get; set; }
private IDatabase DB { get; set; }
public RedisHelper(string connection)
{
Redis = ConnectionMultiplexer.Connect(connection);
DB = Redis.GetDatabase();
} /// <summary>
/// 增加/修改
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool SetValue(string key, string value)
{
return DB.StringSet(key, value);
} /// <summary>
/// 查询
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string GetValue(string key)
{
return DB.StringGet(key);
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool DeleteKey(string key)
{
return DB.KeyDelete(key);
}
}

3、使用

        RedisHelper redisHelper = new RedisHelper("127.0.0.1:6379");
string value = "测试数据";
bool testValue = redisHelper.SetValue("key", value);
string saveValue = redisHelper.GetValue("key"); Console.WriteLine(saveValue); bool newValue = redisHelper.SetValue("key", "NewValue");
saveValue = redisHelper.GetValue("key"); Console.WriteLine(saveValue); bool deleteKey = redisHelper.DeleteKey("key");
string empty = redisHelper.GetValue("key"); Console.WriteLine(empty); Console.ReadKey();

高级玩法: https://www.cnblogs.com/kellynic/p/9803314.html

3、Redis封装

1、RedisHelper

using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks; namespace RedisClientService
{
/// <summary>
/// Redis操作
/// </summary>
public class RedisHelper
{
private int DbNum { get; set; }
private readonly ConnectionMultiplexer _conn;
public string CustomKey; #region 构造函数 public RedisHelper(int dbNum = )
: this(dbNum, null)
{
} public RedisHelper(int dbNum, string readWriteHosts)
{
DbNum = dbNum;
_conn =
string.IsNullOrWhiteSpace(readWriteHosts) ?
RedisConnectionHelp.Instance :
RedisConnectionHelp.GetConnectionMultiplexer(readWriteHosts);
} #endregion #region String #region 同步方法 /// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public bool StringSet(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.StringSet(key, value, expiry));
} /// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public bool StringSet(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return Do(db => db.StringSet(newkeyValues.ToArray())); } /// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool StringSet<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return Do(db => db.StringSet(key, json, expiry));
} /// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public string StringGet(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.StringGet(key));
} /// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public RedisValue[] StringGet(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return Do(db => db.StringGet(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T StringGet<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db => ConvertObj<T>(db.StringGet(key)));
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double StringIncrement(string key, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.StringIncrement(key, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double StringDecrement(string key, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.StringDecrement(key, val));
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 保存单个key value
/// </summary>
/// <param name="key">Redis Key</param>
/// <param name="value">保存的值</param>
/// <param name="expiry">过期时间</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(string key, string value, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return await Do(db => db.StringSetAsync(key, value, expiry));
} /// <summary>
/// 保存多个key value
/// </summary>
/// <param name="keyValues">键值对</param>
/// <returns></returns>
public async Task<bool> StringSetAsync(List<KeyValuePair<RedisKey, RedisValue>> keyValues)
{
List<KeyValuePair<RedisKey, RedisValue>> newkeyValues =
keyValues.Select(p => new KeyValuePair<RedisKey, RedisValue>(AddSysCustomKey(p.Key), p.Value)).ToList();
return await Do(db => db.StringSetAsync(newkeyValues.ToArray()));
} /// <summary>
/// 保存一个对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="obj"></param>
/// <param name="expiry"></param>
/// <returns></returns>
public async Task<bool> StringSetAsync<T>(string key, T obj, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
string json = ConvertJson(obj);
return await Do(db => db.StringSetAsync(key, json, expiry));
} /// <summary>
/// 获取单个key的值
/// </summary>
/// <param name="key">Redis Key</param>
/// <returns></returns>
public async Task<string> StringGetAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(db => db.StringGetAsync(key));
} /// <summary>
/// 获取多个Key
/// </summary>
/// <param name="listKey">Redis Key集合</param>
/// <returns></returns>
public async Task<RedisValue[]> StringGetAsync(List<string> listKey)
{
List<string> newKeys = listKey.Select(AddSysCustomKey).ToList();
return await Do(db => db.StringGetAsync(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 获取一个key的对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> StringGetAsync<T>(string key)
{
key = AddSysCustomKey(key);
string result = await Do(db => db.StringGetAsync(key));
return ConvertObj<T>(result);
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> StringIncrementAsync(string key, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.StringIncrementAsync(key, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> StringDecrementAsync(string key, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.StringDecrementAsync(key, val));
} #endregion 异步方法 #endregion #region Hash #region 同步方法 /// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashExists(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashExists(key, dataKey));
} /// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool HashSet<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string json = ConvertJson(t);
return db.HashSet(key, dataKey, json);
});
} /// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public bool HashDelete(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db => db.HashDelete(key, dataKey));
} /// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public long HashDelete(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return Do(db => db.HashDelete(key, dataKeys.ToArray()));
} /// <summary>
/// 获取hash值列表,返回HashEntry[]
/// </summary>
/// <typeparam name="T">HashEntry[]</typeparam>
/// <param name="key"></param>
/// <returns></returns>
public HashEntry[] HashGetAll(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.HashGetAll(key);
return value;
});
} /// <summary>
/// 获取hash值列表,返回 List<T>,不带条件查询
/// </summary>
/// <typeparam name="T">List<T></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public IList<T> HashGetAll<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var values = db.HashGetAll(key).Select(m => m.Value);
return ConvetList<T>(values);
});
} /// <summary>
/// 获取hash值列表,返回 List<T>,不带条件查询
/// </summary>
/// <typeparam name="T">List<T></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public IEnumerable<T> HashGetEnumerableAll<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var values = db.HashGetAll(key).Select(m => m.Value);
return ConvetEnumerable<T>(values);
});
} /// <summary>
/// 获取hash值列表,返回 List<T>,不带条件查询
/// </summary>
/// <typeparam name="T">List<T></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public IEnumerable<T> HashValuesAsync<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var values = db.HashValuesAsync(key).Result;
return ConvetEnumerable<T>(values);
});
} ///// <summary>
///// 获取hash值列表,返回 List<T>
///// </summary>
///// <typeparam name="T"></typeparam>
///// <param name="key"></param>
///// <param name="strwhere"></param>
///// <returns></returns>
//public List<T> HashGetAll<T>(string key, string strwhere)
//{
// key = AddSysCustomKey(key);
// var db = _conn.GetDatabase(DbNum);
// var values = db.HashGetAll(key);
// if (values != null && values.Length > 0 && !string.IsNullOrWhiteSpace(strwhere))
// { // }
//} /// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public T HashGet<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
return Do(db =>
{
string value = db.HashGet(key, dataKey);
return ConvertObj<T>(value);
});
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public double HashIncrement(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.HashIncrement(key, dataKey, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public double HashDecrement(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return Do(db => db.HashDecrement(key, dataKey, val));
} /// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public List<T> HashKeys<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
RedisValue[] values = db.HashKeys(key);
return ConvetList<T>(values);
});
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 判断某个数据是否已经被缓存
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashExistsAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashExistsAsync(key, dataKey));
} /// <summary>
/// 存储数据到hash表
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="t"></param>
/// <returns></returns>
public async Task<bool> HashSetAsync<T>(string key, string dataKey, T t)
{
key = AddSysCustomKey(key);
return await Do(db =>
{
string json = ConvertJson(t);
return db.HashSetAsync(key, dataKey, json);
});
} /// <summary>
/// 移除hash中的某值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<bool> HashDeleteAsync(string key, string dataKey)
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDeleteAsync(key, dataKey));
} /// <summary>
/// 移除hash中的多个值
/// </summary>
/// <param name="key"></param>
/// <param name="dataKeys"></param>
/// <returns></returns>
public async Task<long> HashDeleteAsync(string key, List<RedisValue> dataKeys)
{
key = AddSysCustomKey(key);
//List<RedisValue> dataKeys1 = new List<RedisValue>() {"1","2"};
return await Do(db => db.HashDeleteAsync(key, dataKeys.ToArray()));
} /// <summary>
/// 从hash表获取数据
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <returns></returns>
public async Task<T> HashGeAsync<T>(string key, string dataKey)
{
key = AddSysCustomKey(key);
string value = await Do(db => db.HashGetAsync(key, dataKey));
return ConvertObj<T>(value);
} /// <summary>
/// 为数字增长val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>增长后的值</returns>
public async Task<double> HashIncrementAsync(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.HashIncrementAsync(key, dataKey, val));
} /// <summary>
/// 为数字减少val
/// </summary>
/// <param name="key"></param>
/// <param name="dataKey"></param>
/// <param name="val">可以为负</param>
/// <returns>减少后的值</returns>
public async Task<double> HashDecrementAsync(string key, string dataKey, double val = )
{
key = AddSysCustomKey(key);
return await Do(db => db.HashDecrementAsync(key, dataKey, val));
} /// <summary>
/// 获取hashkey所有Redis key
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> HashKeysAsync<T>(string key)
{
key = AddSysCustomKey(key);
RedisValue[] values = await Do(db => db.HashKeysAsync(key));
return ConvetList<T>(values);
} #endregion 异步方法 #endregion #region List #region 同步方法 /// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRemove(key, ConvertJson(value)));
} /// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> ListRange<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.ListRange(key);
return ConvetList<T>(values);
});
} /// <summary>
/// 返回list的数目
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public int ListRangeCount(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
return redis.ListRange(key).Length;
});
} /// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, ConvertJson(value)));
} /// <summary>
/// List string类型入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListRightStringPush(string key, string value)
{
key = AddSysCustomKey(key);
Do(db => db.ListRightPush(key, value));
} /// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj<T>(value);
});
} /// <summary>
/// List string类型出队
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public string ListRightStringPop(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return value.ToString();
});
} /// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void ListLeftPush<T>(string key, T value)
{
key = AddSysCustomKey(key);
Do(db => db.ListLeftPush(key, ConvertJson(value)));
} /// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj<T>(value);
});
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long ListLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.ListLength(key));
} #endregion 同步方法 #region 异步方法 /// <summary>
/// 移除指定ListId的内部List的值
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRemoveAsync(key, ConvertJson(value)));
} /// <summary>
/// 获取指定key的List
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> ListRangeAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.ListRangeAsync(key));
return ConvetList<T>(values);
} /// <summary>
/// 入队
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListRightPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListRightPushAsync(key, ConvertJson(value)));
} /// <summary>
/// 出队
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListRightPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListRightPopAsync(key));
return ConvertObj<T>(value);
} /// <summary>
/// 入栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<long> ListLeftPushAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(db => db.ListLeftPushAsync(key, ConvertJson(value)));
} /// <summary>
/// 出栈
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public async Task<T> ListLeftPopAsync<T>(string key)
{
key = AddSysCustomKey(key);
var value = await Do(db => db.ListLeftPopAsync(key));
return ConvertObj<T>(value);
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> ListLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.ListLengthAsync(key));
} #endregion 异步方法 #endregion #region Set /// <summary>
/// 返回set总条数
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public long SetLength<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SetLength(key));
} /// <summary>
/// 添加Set
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool SetAdd<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SetAdd(key, ConvertJson<T>(value)));
} /// <summary>
/// 删除Set
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="t"></param>
/// <returns></returns>
public bool SetRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SetRemove(key, ConvertJson<T>(value)));
} /// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> SetMembers<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SetMembers(key);
return ConvetList<T>(values);
});
} #region Set分页
/// <summary>
/// Set分页
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="pattern"></param>
/// <param name="pageSize"></param>
/// <param name="cursor"></param>
/// <param name="pageOffset"></param>
/// <param name="flags"></param>
/// <returns></returns>
public List<T> SetScan<T>(RedisKey key, string pattern = "", int pageSize = , long cursor = , int pageOffset = , CommandFlags flags = CommandFlags.None)
{
key = AddSysCustomKey(key);
var values = _conn.GetDatabase(DbNum).SetScan(key, pattern, pageSize, cursor, pageOffset, flags).ToArray();
return ConvetList<T>(values);
}
#endregion /// <summary>
/// 批量插入Set
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="key"></param>
/// <returns></returns>
public void SetBatchAdd<T>(IEnumerable<T> t, string key)
{
if (t != null && t.Count() > )
{
var Batch = _conn.GetDatabase(DbNum).CreateBatch();
var list = t.Select(item =>
{
return (RedisValue)JsonConvert.SerializeObject(item);
});
Batch.SetAddAsync(key, list.ToArray(), CommandFlags.None);
Batch.Execute();
}
} #endregion #region SortedSet 有序集合 #region 同步方法 /// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public bool SortedSetAdd<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetAdd(key, ConvertJson<T>(value), score));
} public long SortedSetAdd(string key, SortedSetEntry[] value)
{
return Do(redis => redis.SortedSetAdd(key, value));
} /// <summary>
/// 批量插入SortedSet
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="key">redis键</param>
/// <param name="scorePropertyName">score属性名称</param>
public void SortedSetBatchAdd<T>(IEnumerable<T> t, string key, string scorePropertyName)
{
double i = 1d;
if (t != null && t.Count() > )
{
var Batch = _conn.GetDatabase(DbNum).CreateBatch();
var list = t.Select(item =>
{
double score = !string.IsNullOrWhiteSpace(scorePropertyName) ? double.Parse(GetObjectPropertyValue<T>(item, scorePropertyName).ToString()) : (i++);
return new SortedSetEntry(JsonConvert.SerializeObject(item), score);
});
Batch.SortedSetAddAsync(key, list.ToArray(), CommandFlags.None);
Batch.Execute();
}
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public bool SortedSetRemove<T>(string key, T value)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetRemove(key, ConvertJson(value)));
} /// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public List<T> SortedSetRangeByRank<T>(string key)
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key);
return ConvetList<T>(values);
});
} /// <summary>
/// 获取条件指定的数据-分页
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="start"></param>
/// <param name="stop"></param>
/// <returns></returns>
public List<T> SortedSetRangeByRankPage<T>(string key, long start = , long stop = -, int order = , int cmdFlags = )
{
key = AddSysCustomKey(key);
return Do(redis =>
{
var values = redis.SortedSetRangeByRank(key, start, stop, order == ? Order.Ascending : Order.Descending, (CommandFlags)cmdFlags);
return ConvetList<T>(values);
});
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public long SortedSetLength(string key)
{
key = AddSysCustomKey(key);
return Do(redis => redis.SortedSetLength(key));
}
#endregion #region 异步方法
/// <summary>
/// 添加
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <param name="score"></param>
public async Task<bool> SortedSetAddAsync<T>(string key, T value, double score)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetAddAsync(key, ConvertJson<T>(value), score));
} /// <summary>
/// 删除
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
public async Task<bool> SortedSetRemoveAsync<T>(string key, T value)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetRemoveAsync(key, ConvertJson(value)));
} /// <summary>
/// 获取全部
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<List<T>> SortedSetRangeByRankAsync<T>(string key)
{
key = AddSysCustomKey(key);
var values = await Do(redis => redis.SortedSetRangeByRankAsync(key));
return ConvetList<T>(values);
} /// <summary>
/// 获取集合中的数量
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public async Task<long> SortedSetLengthAsync(string key)
{
key = AddSysCustomKey(key);
return await Do(redis => redis.SortedSetLengthAsync(key));
} #endregion #endregion #region key /// <summary>
/// 删除单个key
/// </summary>
/// <param name="key">redis key</param>
/// <returns>是否删除成功</returns>
public bool KeyDelete(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyDelete(key));
} /// <summary>
/// 删除多个key
/// </summary>
/// <param name="keys">rediskey</param>
/// <returns>成功删除的个数</returns>
public long KeyDelete(List<string> keys)
{
List<string> newKeys = keys.Select(AddSysCustomKey).ToList();
return Do(db => db.KeyDelete(ConvertRedisKeys(newKeys)));
} /// <summary>
/// 判断key是否存储
/// </summary>
/// <param name="key">redis key</param>
/// <returns></returns>
public bool KeyExists(string key)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExists(key));
} /// <summary>
/// 重新命名key
/// </summary>
/// <param name="key">就的redis key</param>
/// <param name="newKey">新的redis key</param>
/// <returns></returns>
public bool KeyRename(string key, string newKey)
{
key = AddSysCustomKey(key);
return Do(db => db.KeyRename(key, newKey));
} /// <summary>
/// 设置Key的时间
/// </summary>
/// <param name="key">redis key</param>
/// <param name="expiry"></param>
/// <returns></returns>
public bool KeyExpire(string key, TimeSpan? expiry = default(TimeSpan?))
{
key = AddSysCustomKey(key);
return Do(db => db.KeyExpire(key, expiry));
} #endregion #region 队列
//public bool EnqueueItemOnList(string key)
//{
// //key = AddSysCustomKey(key);
// //return Do(db => db.en);
// // return Do(db => db.list); //}
//public bool KeyDelete(string key)
//{
// key = AddSysCustomKey(key);
// return Do(db => db.KeyDelete(key));
//}
#endregion #region 发布订阅 /// <summary>
/// Redis发布订阅 订阅
/// </summary>
/// <param name="subChannel"></param>
/// <param name="handler"></param>
public void Subscribe(string subChannel, Action<RedisChannel, RedisValue> handler = null)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Subscribe(subChannel, (channel, message) =>
{
if (handler == null)
{
Console.WriteLine(subChannel + " 订阅收到消息:" + message);
}
else
{
handler(channel, message);
}
});
} /// <summary>
/// Redis发布订阅 发布
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="channel"></param>
/// <param name="msg"></param>
/// <returns></returns>
public long Publish<T>(string channel, T msg)
{
ISubscriber sub = _conn.GetSubscriber();
return sub.Publish(channel, ConvertJson(msg));
} /// <summary>
/// Redis发布订阅 取消订阅
/// </summary>
/// <param name="channel"></param>
public void Unsubscribe(string channel)
{
ISubscriber sub = _conn.GetSubscriber();
sub.Unsubscribe(channel);
} /// <summary>
/// Redis发布订阅 取消全部订阅
/// </summary>
public void UnsubscribeAll()
{
ISubscriber sub = _conn.GetSubscriber();
sub.UnsubscribeAll();
} #endregion #region 其他 public ITransaction CreateTransaction()
{
return GetDatabase().CreateTransaction();
} public IDatabase GetDatabase()
{
return _conn.GetDatabase(DbNum);
} public IServer GetServer(string hostAndPort)
{
return _conn.GetServer(hostAndPort);
} /// <summary>
/// 设置前缀
/// </summary>
/// <param name="customKey"></param>
public void SetSysCustomKey(string customKey)
{
CustomKey = customKey;
} #endregion #region 辅助方法 private string AddSysCustomKey(string oldKey)
{
var prefixKey = CustomKey ?? RedisConnectionHelp.SysCustomKey;
return prefixKey + oldKey;
} private T Do<T>(Func<IDatabase, T> func)
{
var database = _conn.GetDatabase(DbNum);
return func(database);
} private string ConvertJson<T>(T value)
{
string result = value is string ? value.ToString() : JsonConvert.SerializeObject(value);
return result;
} private T ConvertObj<T>(RedisValue value)
{
return JsonConvert.DeserializeObject<T>(value);
} private List<T> ConvetList<T>(RedisValue[] values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
} private List<T> ConvetList<T>(IEnumerable<RedisValue> values)
{
List<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
} private IEnumerable<T> ConvetEnumerable<T>(IEnumerable<RedisValue> values)
{
IList<T> result = new List<T>();
foreach (var item in values)
{
var model = ConvertObj<T>(item);
result.Add(model);
}
return result;
} private RedisKey[] ConvertRedisKeys(List<string> redisKeys)
{
return redisKeys.Select(redisKey => (RedisKey)redisKey).ToArray();
} /// <summary>
/// 反射实体的值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="propertyname"></param>
/// <returns></returns>
private string GetObjectPropertyValue<T>(T t, string propertyname)
{
Type type = typeof(T);
PropertyInfo property = type.GetProperty(propertyname);
if (property == null) return string.Empty;
object o = property.GetValue(t, null);
if (o == null) return string.Empty;
return o.ToString();
}
#endregion
}
}

2、RedisConnectionHelp

using Global;
using StackExchange.Redis;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace RedisClientService
{
/// <summary>
/// ConnectionMultiplexer对象管理帮助类
/// </summary>
public static class RedisConnectionHelp
{
//系统自定义Key前缀
public static string SysCustomKey = ConfigurationManager.AppSettings["redisKey"] ?? "";
private static readonly object Locker = new object();
private static ConnectionMultiplexer _instance;
private static readonly ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionCache = new ConcurrentDictionary<string, ConnectionMultiplexer>(); #region 单例获取
/// <summary>
/// 单例获取
/// </summary>
public static ConnectionMultiplexer Instance
{
get
{
if (_instance == null)
{
lock (Locker)
{
if (_instance == null || !_instance.IsConnected)
{
_instance = GetManager();
}
}
}
return _instance;
}
}
#endregion #region 缓存获取
/// <summary>
/// 缓存获取
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
public static ConnectionMultiplexer GetConnectionMultiplexer(string connectionString)
{
if (!ConnectionCache.ContainsKey(connectionString))
{
ConnectionCache[connectionString] = GetManager(connectionString);
}
return ConnectionCache[connectionString]; // return GetManager(connectionString);
} /// <summary>
/// 获取管理器
/// </summary>
/// <param name="connectionString"></param>
/// <returns></returns>
private static ConnectionMultiplexer GetManager(string connectionString = null)
{
// connectionString = connectionString ?? ReadRedisConnectionString;
connectionString = connectionString ?? RedisGlobals.ReadAndWriteRedisConnectionString; //ConfigurationOptions options = ConfigurationOptions.Parse(connectionString);
//options.ConnectTimeout = 1000;
var connect = ConnectionMultiplexer.Connect(connectionString); //注册如下事件--测试专用
//connect.ConnectionFailed += MuxerConnectionFailed;
//connect.ConnectionRestored += MuxerConnectionRestored;
//connect.ErrorMessage += MuxerErrorMessage;
//connect.ConfigurationChanged += MuxerConfigurationChanged;
//connect.HashSlotMoved += MuxerHashSlotMoved;
//connect.InternalError += MuxerInternalError;
return connect;
}
#endregion #region 事件 ///// <summary>
///// 配置更改时
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
//{
// LogHelper.WriteLog("Configuration changed: " + e.EndPoint);
//} ///// <summary>
///// 发生错误时
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
//{
// LogHelper.WriteLog("ErrorMessage: " + e.Message);
//} ///// <summary>
///// 重新建立连接之前的错误
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
//{
// LogHelper.WriteLog("ConnectionRestored: " + e.EndPoint);
//} ///// <summary>
///// 连接失败 , 如果重新连接成功你将不会收到这个通知
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
//{
// LogHelper.WriteLog("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType + (e.Exception == null ? "" : (", " + e.Exception.Message)));
//} ///// <summary>
///// 更改集群
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
//{
// LogHelper.WriteLog("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
//} ///// <summary>
///// redis类库错误
///// </summary>
///// <param name="sender"></param>
///// <param name="e"></param>
//private static void MuxerInternalError(object sender, InternalErrorEventArgs e)
//{
// LogHelper.WriteLog("InternalError:Message" + e.Exception.Message);
//} #endregion 事件
}
}

注意:更改

配置appsetting.json

或者将这个写死

第一个地方:

第二个地方:

测试结果

list

注意:

        /// <summary>
/// 出队||将数据从最右边边的(就是最尾部的) 并且从redis的list里面移除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListRightPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListRightPop(key);
return ConvertObj<T>(value);
});
} /// <summary>
/// 出栈||将数据从最左边的(就是最开始的) 并且从redis的list里面移除
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public T ListLeftPop<T>(string key)
{
key = AddSysCustomKey(key);
return Do(db =>
{
var value = db.ListLeftPop(key);
return ConvertObj<T>(value);
});
}

Hash

这种存储list数组(适用于三层数据结构,前面两个键最后一个值分别是key、datakey、value)

注意: redisHelp.HashSet("a",str1,str2);   "a",str1这两个参数原本有就覆盖

Set

一、Signalr WebApi客服-客户链接+Redis的更多相关文章

  1. 一、Signalr WebApi客服

    一.搭建环境 (redis服务) 链接测试 二.项目搭建 参考 1.搭建项目(直接项目-不包含MVC以及API) 项目结构 但是需要访问(所以还需要添加控制器Api的模式)选择Api 添加类库一个专门 ...

  2. 一、Signalr WebApi客服-数据传输实体

    一.定义消息传输的格式 res不受自己控制 接受ret是自己处理,但是必须包含头像等一系列信息,所有发送的时候消息也是需要传头像的.

  3. 用SignalR 2.0开发客服系统[系列3:实现点对点通讯]

    前言 交流群:195866844 目录: 用SignalR 2.0开发客服系统[系列1:实现群发通讯] 用SignalR 2.0开发客服系统[系列2:实现聊天室] 真的很感谢大家的支持,今天发表系列3 ...

  4. 用SignalR 2.0开发客服系统[系列4:负载均衡的情况下使用SignalR]

    前言 交流群:195866844 目录: 用SignalR 2.0开发客服系统[系列1:实现群发通讯] 用SignalR 2.0开发客服系统[系列2:实现聊天室] 用SignalR 2.0开发客服系统 ...

  5. 如何用JS判断推广链接所属的客服

    今天有一个客户提出一个需求:网站有多个在线客服,每个客服都有自己的网站推广链接,当访客通过该客服的推广链接进入网站时,必须指定由该客服接待. 我的实现思路是获取推广链接中特定字符,然后判断字符对应的客 ...

  6. ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室(十四)之漏掉的客服消息

    前言 不知不觉已经十四篇了,其实已经没有什么可写了.但是突然发现layim中带的客服功能没有用到.于是乎,抽点时间完成吧.其实之前的工作已经把客服功能完成了一大半,剩下的我们稍微调整即可.今天的演示我 ...

  7. ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(二) 实现聊天室连接

    上一篇已经简单介绍了layim WebUI即时通讯组件和获取数据的后台方法.现在要讨论的是SingalR的内容,之前都是直接贴代码.那么在贴代码之前先分析一下业务模型,顺便简单讲一下SingalR里的 ...

  8. 转载 ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(三) 激动人心的时刻到啦,实现1v1聊天

    ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(三) 激动人心的时刻到啦,实现1v1聊天   看起来挺简单,细节还是很多的,好,接上一篇,我们已经成功连接singalR服务器 ...

  9. 转载 ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(一) 整理基础数据

    ASP.NET SignalR 与LayIM配合,轻松实现网站客服聊天室(一) 整理基础数据   最近碰巧发现一款比较好的Web即时通讯前端组件,layim,百度关键字即可,我下面要做的就是基于这个前 ...

随机推荐

  1. spark 笔记 8: Stage

    Stage 是一组独立的任务,他们在一个job中执行相同的功能(function),功能的划分是以shuffle为边界的.DAG调度器以拓扑顺序执行同一个Stage中的task. /** * A st ...

  2. oracle11g RMAN catalog的基本使用

    编辑 /etc/hosts文件 tnsnames.ora文件 创建SQL> create tablespace ts_rman_catalog datafile '/u01/app/oracle ...

  3. 全面解读php-函数

    一.静态变量 二.函数的参数 三.函数的引用返回 四.外部文件的导入 五.内置函数 1.时间日期函数 2.IP处理函数 3.打印函数: 分类 函数名 说明 语言结构 print() 只能打印一个变量 ...

  4. EC

  5. Windows下搭建Docker与Kubernetes(DevOps一)

    Docker与Kubernetes (二)搭建 开通  Hyper-V 安装Docker for Windows 开通Kubernetes 3.关键概念 PodKubernetes 中的最小单元,一个 ...

  6. python之拷贝文件

    做了个小实验, 用于拷贝文件夹下面的jpg. 用于拓展, 可以引入类和方法, 拷贝你指定的任意类型的文件. import os src = 'C:\\Users\\Administrator\\Des ...

  7. 配置Toad链接远程Oracle数据库

    当前环境: 本机系统:Win7 64位 Toad版本:11 32位 数据库:Oracle 10g =================================== 与PLSQL Develope ...

  8. OpenStack 2018 年终盘点

    目录 文章目录 目录 前言 OpenStack 一年来的成长 Nova Cinder Neutron Ironic Cyborg Octavia Kolla Magnum Zun Kuryr 从 Op ...

  9. rsync启动脚本

    rsync启动脚本 01 #!/bin/bash  www.ahlinux.com 02 # 03 # rsyncd      This shell script takes care of star ...

  10. centos7 忘记root密码,如何进入单用户模式。

    init方法 1.centos7的grub2界面会有两个入口,正常系统入口和救援模式: 2.修改grub2引导 在正常系统入口上按下"e",会进入edit模式,搜寻ro那一行,以l ...