Unity-Redis数据存储

1.Redis 安装测试:

安装:

安装包 链接:https://pan.baidu.com/s/1BzuqRNJHW1MiB4xm4UT4MA 提取码:pvrj

使用:

运行包内 redis-server.exe 启动 Redis 服务 ,运行包内 redis-cli.exe 启动客户端 (本地自联)

远程到主机为 127.0.0.1,端口为 6379 ,密码为 mypass 的 redis 服务上 : redis-cli -h 127.0.0.1 -p 6379 -a "mypass"

命令:

检测连接 ping PONG

增:set key value (setnx key value只有在 key 不存在时设置 key 的值 , exists key 存在 (integer) 1,不存在 (integer) 0)

删:del key (命令执行后输出 (integer) 1,否则将输出 (integer) 0)

改: set key value (rename key newkey 修改key, renamenx key newkey 仅当 newkey 不存在时,将 key 改名为 newkey)

查: get key (type key 查看value类型 ,strlen key 返回 key 所储存的字符串值的长度)

2.Unity-Redis 存储调用:

untiy工程需添加dll:链接:https://pan.baidu.com/s/1mPI4HYPTP5rfi3q-C3y-WQ 提取码:0wod

cs 复制代码
using UnityEngine;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
 
public class Unity_Redis : MonoBehaviour
{
    string exePath = @"F:\Redis\Redis-x64-5.0.10\redis-server.exe";
    //string exePath = Application.dataPath + "/Resources/redis-server.exe";
    RedisClient redisClient = new RedisClient("127.0.0.1", 6379);
      
    private void Start()
    {
        //var P_exe = Process.Start(exePath);
        //Application.OpenURL(exePath);
 
        Process pro = new Process();
        pro.StartInfo.FileName = exePath;
        pro.StartInfo.UseShellExecute = true;
        pro.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        pro.Start();
    }
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Q))
        {
            redisClient.Add<string>("name", "xiaolang");
            UnityEngine.Debug.Log("添加:name -- " + redisClient.Get<string>("name"));
        }
        if (Input.GetKeyDown(KeyCode.W))
        {
            UnityEngine.Debug.Log("删除:name -- " + redisClient.Get<string>("name"));
            redisClient.Del("name");
        }
        if (Input.GetKeyDown(KeyCode.Delete))
        {
            redisClient.FlushAll();
            UnityEngine.Debug.Log("清理Redis");
        }
    }
    private void OnDestroy()
    {
        KillProcess("redis-server");
    }
    private void KillProcess(string processName)
    {
        //processName是exe的文件名
 
        Process[] processes = Process.GetProcesses();
        foreach (Process process in processes)
        {
            try
            {
                if (!process.HasExited)
                {
                    if (process.ProcessName == processName)
                    {
                        process.Kill();
                        UnityEngine.Debug.Log("已关闭进程");
                    }
                }
            }
            catch (Exception e)
            {
                UnityEngine.Debug.Log(e.ToString());
            }
        }
    }
}

参考:https://www.jianshu.com/p/fab041e93b52