使用MVC + CacheManager,调用Redis实现数据存储操作

在这里插入图片描述

1//FileOperation控制器

using Day18ExamRedisMVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Day18ExamRedisMVC.Controllers
{
public class FileOperationController : Controller
{
APIFileHelp help = new APIFileHelp();

    // GET: FileOption
    public ActionResult Index()
    {
        return View();
    }

    //实现头像上传
    public string UpLoad()
    {
        return help.UpLoad();
    }
}

}

2//User控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Day18ExamRedisMVC.Models;
using Day18ExamRedisMVC.RedisCache;

namespace Day18ExamRedisMVC.Controllers
{
public class UserController : Controller
{
RedisHelper redis = new RedisHelper();

    // GET: User
    public ActionResult Main()
    {
        return View();
    }

    //信息保存到Redis数据库中
    [HttpPost]
    public int AddUserInfo(UserInfo mod)
    {
        return redis.AddUserInfo("userInfo",mod);
    }

    //显示出注册的用户信息
    [HttpGet]
    public ActionResult ShowUserInfo()
    {
        var list = redis.GetUserInfos("userInfo");
        return View(list);
    }
}

}

3//Redis_Client类单例模式配置Redis服务器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;

namespace Day18ExamRedisMVC.RedisCache
{
///
/// 单例模式配置Redis服务器
///
public class Redis_Client
{
//私有构造函数
private Redis_Client() { }
//私有静态字段
private static RedisClient redis;
//安全锁
private static object Lock = new object();

    //公用静态方法
    public static RedisClient GetRedis()
    {
        //验证是否为空
        if (redis==null)
        {
            //安全锁双重验证
            lock (Lock)
            {
                if (redis==null)
                {
                    //配置Redis
                    redis = new RedisClient("127.0.0.1", 6379);
                    return redis;
                }
            }
        }
        return redis;
    }
}

}

4//RedisHelper类

using Day18ExamRedisMVC.Models;
using ServiceStack.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Day18ExamRedisMVC.RedisCache
{
public class RedisHelper
{
RedisClient redis = Redis_Client.GetRedis();

    public int AddUserInfo(string userKey,UserInfo mod)
    {
        //判断key是否存在
        if (!redis.ContainsKey(userKey))
        {
            List<UserInfo> list = new List<UserInfo>();
            try
            {
                mod.UId = 1;
                //list添加值
                list.Add(mod);
                //注册信息保存到Redis数据库中
                redis.Set(userKey, list);
                return list.Count;
            }
            catch (Exception)
            {
                return 0;
            }
        }
        else
        {
            //获取redis缓存用户列表数据
            var list = GetUserInfos(userKey);
            try
            {
                //UId自增
                mod.UId = list.OrderByDescending(m => m.UId).FirstOrDefault().UId+1;
                list.Add(mod);
                //缓存赋值
                redis.Set(userKey, list);
                return list.Count;
            }
            catch (Exception)
            {
                return 0;
            }
        }
    }

    //获取Redis缓存用户列表数据
    public List<UserInfo> GetUserInfos(string userKey)
    {
        return redis.Get<List<UserInfo>>(userKey);
    }
}

}

5//Main前台页面

@{
Layout = null;
}

<meta name="viewport" content="width=device-width" />
<title>Main</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<script src="~/Content/jquery-3.3.1.js"></script>
<style>
    #div {
        width: 500px;
        margin: auto;
        margin-top: 100px;
        border: 1px solid black;
        padding: 30px;
    }
    #tab td{
        padding:10px;
    }
</style>


<div id="div"> 
    <table id="tab">
        <tr>
            <td>
                <input id="UName" type="text" placeholder="姓名" />
            </td>
            <td rowspan="3">
                <img src="" id="img1" style="width:80px" />
            </td>
        </tr>
        <tr>
            <td>
                <input id="Radio1" name="1" type="radio" checked="checked" />男
                <input id="Radio2" name="1" type="radio" />女
            </td>
        </tr>
        <tr>
            <td>
                <input id="UAge" type="text" placeholder="年龄" />
            </td>
        </tr>
        <tr>
            <td>
                <select id="UStudy">
                    <option value="0">选择学历</option>
                    <option>高中</option>
                    <option>大专</option>
                    <option>本科</option>
                    <option>博士</option>
                    <option>研究生</option>
                    <option>硕士以上</option>
                </select>
            </td>
            <td>
                <input id="File1" type="file" />
                <a href="javascript:upLoadImg()">上传头像</a>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <textarea id="UMomox" rows="5" cols="40" placeholder="座右铭"></textarea>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <input id="Button1" type="button" value="注册" class="btn btn-primary" onclick="btnGo()" />
            </td>
        </tr>
    </table>
</div>



//实现头像上传
function upLoadImg() {
    var formData = new FormData();
    var file = document.getElementById("File1").files[0];
    formData.append("fileInfo", file);
    $.ajax({
        url: "/FileOperation/UpLoad",
        type: "POST",
        data: formData,
        contentType: false,//必须false才会自动加上正确的Content-Type
        processData: false,//必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理
        success: function (data) {
            if (data == "-1") {
                alert("只允许上传指定格式文件!.doc,.xls,.png,.jpg")
            }
            else if (data == "0") {
                alert("请选择照片!");
            }
            else {
                $("#img1").attr("src", data);
            }
        },
        error: function (data) {
            alert("上传失败!");
        }
    });
}

function btnGo() {
    var obj = {};
    obj.UName = $("#UName").val();
    obj.USex = Radio1.checked ? true : false;
    obj.UAge = $("#UAge").val();
    obj.UStudy = $("#UStudy").val();
    obj.UMomox = $("#UMomox").val();
    obj.UImg = $("#img1").attr("src");
    $.ajax({
        url: "/User/AddUserInfo",
        data: obj,
        dataType: "json",
        type: "post",
        success: function (data) {
            if (data > 0) {
                alert("保存成功!");
                location.href ="/User/ShowUserInfo"
            }
            else {
                alert("保存失败!");
            }
        }
    })
}

6//ShowUserInfo前台页面

@{
Layout = null;
}
@using Day18ExamRedisMVC.Models;
@model List

<meta name="viewport" content="width=device-width" />
<title>ShowUserInfo</title>
<link href="~/Content/bootstrap.css" rel="stylesheet" />


<div> 
    <table class="table table-striped">
        <tr>
            <td>用户Id</td>
            <td>用户姓名</td>
            <td>用户头像</td>
            <td>用户性别</td>
            <td>用户年龄</td>
            <td>用户学历</td>
            <td>用户座右铭</td>
        </tr>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.UId</td>
                <td>@item.UName</td>
                <td><img src="@item.UImg" style="width:50px" /></td>
                <td>@(item.USex?"男":"女")</td>
                <td>@item.UAge</td>
                <td>@item.UStudy</td>
                <td>@item.UMomox</td>
            </tr>
        }
    </table>
</div>
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页