首页 > 数据库 >net core Web API 使用 Redis

net core Web API 使用 Redis

时间:2024-03-21 09:56:50浏览次数:15  
标签:core return string redisConnection Web Redis value key public

1.新建 Web API api
2.新建 类库 Service 安装 StackExchange.Redis
2.1 Service中 新建 Redis文件夹,并创建 接口IRedisService和类 RedisSerivce

点击查看代码
public interface IRedisService{
  //获取 Redis 缓存值
  string GetValue(string key);

  //获取值,并序列化
  TEntity Get<TEntity>(string key);

  //保存
  bool Set(string key, object value, TimeSpan cacheTime);

  //新增
  bool SetValue(string key, byte[] value);

  //判断是否存在
  bool Get(string key);

  //移除某一个缓存值
  bool Remove(string key);

  //全部清除
  bool Clear();
}

2.2 RedisService 中 引用 using StackExchange.Redis

点击查看代码
public class RedisCacheManage : IRedisCacheManage
{
    private readonly string redisConnectionString;
    private volatile ConnectionMultiplexer redisConnection;
    private readonly object redisConnectionLock = new object();
    public RedisCacheManage() {
        string redisCOnfiguration = "127.0.0.1:6379";//Appsetting.app(new string[] {"AppSettings","RedisCaching","ConnectionString" });
        if (string.IsNullOrWhiteSpace(redisCOnfiguration)) {
            throw new ArgumentException("redis config is empty!",nameof(redisCOnfiguration));
        }
        this.redisConnectionString = redisCOnfiguration;
        this.redisConnection = GetRedisConnection();
    }
    /// <summary>
    /// 核心代码,获取连接实例
    /// 通过双if 夹lock的方式,实现单例模式
    /// </summary>
    /// <returns></returns>
    private ConnectionMultiplexer GetRedisConnection()
    {
        //如果已经连接实例,直接返回
        if (this.redisConnection != null && this.redisConnection.IsConnected)
        {
            return this.redisConnection;
        }
        //加锁,防止异步编程中,出现单例无效的问题
        lock (redisConnectionLock)
        {
            if (this.redisConnection != null)
            {
                //释放redis连接
                this.redisConnection.Dispose();
            }
            try
            {
                this.redisConnection = ConnectionMultiplexer.Connect(redisConnectionString);
            }
            catch (Exception)
            {

                throw new Exception("Redis服务未启用,请开启该服务");
            }
        }
        return this.redisConnection;
    }
    public bool Clear()
    {
        bool res = true;
        foreach (var endPoint in this.GetRedisConnection().GetEndPoints())
        {
            var server = this.GetRedisConnection().GetServer(endPoint);
            foreach (var key in server.Keys())
            {
                res=redisConnection.GetDatabase().KeyDelete(key);
            }
        }
        return res;
    }

    public bool Get(string key)
    {
        return redisConnection.GetDatabase().KeyExists(key);
    }

    public string GetValue(string key)
    {
        return redisConnection.GetDatabase().StringGet(key);
    }

    public TEntity Get<TEntity>(string key)
    {
        var value = redisConnection.GetDatabase().StringGet(key);
        if (value.HasValue)
        {
            //需要用的反序列化,将Redis存储的Byte[],进行反序列化
            return SerializeHelper.Deserialize<TEntity>(value);
        }
        else
        {
            return default(TEntity);
        }
    }

    public bool Remove(string key)
    {
        return redisConnection.GetDatabase().KeyDelete(key);
    }

    public bool Set(string key, object value, TimeSpan cacheTime)
    {
        if (value != null)
        {
            //序列化,将object值生成RedisValue
            return redisConnection.GetDatabase().StringSet(key, SerializeHelper.Serialize(value), cacheTime);
        }
        return false;
    }

    public bool SetValue(string key, byte[] value)
    {
        return redisConnection.GetDatabase().StringSet(key, value, TimeSpan.FromSeconds(120));
    }

}

2.3 Service类库中 新建Helper文件夹并创建 SerializeHelper类

点击查看代码
public class SerializeHelper
{
    /// <summary>
    /// 序列化
    /// </summary>
    /// <param name="item"></param>
    /// <returns></returns>
    public static byte[] Serialize(object item) {
        string jsonString = JsonSerializer.Serialize(item);
        return Encoding.UTF8.GetBytes(jsonString);
    }
    /// <summary>
    /// 反序列化
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static TEntity Deserialize<TEntity>(byte[] value) {
        if (value == null)
        {
            return default(TEntity);
        }
        string JsonString = Encoding.UTF8.GetString(value);
        return JsonSerializer.Deserialize<TEntity>(JsonString);
    }
}

3.1 Web API progarm.sc 中依赖注入

builder.Services.AddSingleton<IRedisService, RedisService>();

3.2 Web API 新增API控制器 RedisController.cs

引入
Service.Redis;
Model.Models;

点击查看代码
private readonly IRedisCacheManage _iredisCacheManage;
public RedisController(IRedisCacheManage redisCacheManage) { 
    _iredisCacheManage = redisCacheManage;
}
[HttpGet]
public async Task<IActionResult> Redis(string id) {
    id = "fas21fASdf2asdF";
    var key = $"Redis{id}";
    TUser user = new TUser();
    user.NickName = "张三";
    user.Avator = "/asjd/ajslf.jpg";
    user.State = 0;
    user.PassWord = "123456";
    user.Account = "456789";
    user.ID = id;
    if (_iredisCacheManage.Get<object>(key) != null)
    {
        user = _iredisCacheManage.Get<TUser>(key);
    }
    else {
        //查到对应数据,存入 redis 中
        //...
        _iredisCacheManage.Set(key, user, TimeSpan.FromHours(2));//缓存2小时
    }
    return Ok(user);
}

标签:core,return,string,redisConnection,Web,Redis,value,key,public
From: https://www.cnblogs.com/qx-blog/p/18086600

相关文章

  • 超高并发下,Redis热点数据风险破解
    ★Redis24篇集合1介绍作者是互联网一线研发负责人,所在业务也是业内核心流量来源,经常参与业务预定、积分竞拍、商品秒杀等工作。近期参与多场新员工的面试工作,经常就『超高并发场景下热点数据』可用性保障与候选人进行讨论。本文聚焦一些关键点技术进行讨论,并总结一些热......
  • 9.JavaWeb& javaScript基础
    目录导语:一、JavaWeb概述二、JavaScript基础概念:功能:1.基本语法(1)与html结合方式(2)注释(3)数据类型(4)变量(5)运算符(6)流程控制语句:(7)JS特殊语法:案例:99乘法表2.基本对象(1)Function:函数(方法)对象(2)Array:数组对象(3)Boolean(4)Date:日期对象(5)Math:数学对象(6)Number(7)String(8......
  • JWT(JSON WEB TOKEN)是玩具吗
    JWT当然不是玩具,理解其设计意图,和适用场景自然会发现存在的就是有价值的JWT:JSONWebToken起源和定义JWT(JSONWebToken)是由IETF(InternetEngineeringTaskForce)基于RFC7519规范定义的。它是一种用于在网络应用间传递信息的标准方法。JWT最初由无状态的分布式应用场......
  • CsRedis
    首先需要安装CSRedis包dotnetaddpackageCSRedis创建RedisClient对象,使用哪个库,密码,都可以在这里设置varredis=newRedisClient("localhost:6379");基本操作//写入数据redis.Set("key1","小明");//读取数据varname=redis.Get<string>("key1"......
  • 在非标准Spring组件中(比如websocket)注入Spring管理bean的方法
    privatestaticUserMapperuserMapper;@AutowiredpublicvoidsetUserMapper(UserMapperuserMapper){WebSocketServer.userMapper=userMapper;}WebSocketServer是通过JavaWebSocketAPI创建的,并且由于@ServerEndpoint不是Spring的标准组件注解,直......
  • Linux下生成核心转储core
    为了方便进行分析调试,希望当程序发生崩溃或者收到SIGSEGV、SIGABRT等信号时,系统会生成相应的核心转储文件。核心转储大小限制首先,要检查核心转储的大小限制。可以使用ulimit命令来查看当前用户的核心转储大小限制:ulimit-c如果输出为0,则表示不生成核心转储文件。可以使......
  • web服务器性能评估和监视
         ......
  • Websoket 客户端忽略证书验证
    一、方法一<dependency> <groupId>org.java-websocket</groupId> <artifactId>Java-WebSocket</artifactId> <version>1.5.2</version></dependency>packagecom.neo.websoket;importorg.java_websocket.client.WebSocket......
  • 订单号规则,不能重复。redis去重 redis集合set应用
    订单号规则,不能重复。redis去重redis集合set应用redis锁定商品解决并发售卖问题RedisUtil工具类https://www.cnblogs.com/oktokeep/p/17917833.html需求背景:订单号根据日期反转加上随机数,订单号是否重复,前提是确保当天的订单号不重复,可以确保全局系统中的订单号不重复。//......
  • WebRTC基础使用
    一、什么是WebRTCWebRTC(WebReal-TimeCommunication)是一个由Google、Mozilla、Opera等公司发起的开源项目,它支持网页浏览器进行实时音视频对话。它允许网络应用或者站点,在不借助中间媒介的情况下,建立浏览器之间点对点(Peer-to-Peer)的连接,实现视频流和音频流或者其他任意数据的传......